3

i'm so sorry if this question already asked before,

so what i'm trying to do is to get result like this from my models

$data = $userModel->where('username', 'myname')->find();

my expectation :

$data = [
  'id' => 1,
  'username' => 'myname',
  'fullname' => 'my full name',
]

what i get :

$data = [
  0 => [
    'id' => 1,
    'username' => 'myname',
    'fullname' => 'my full name',
  ]
]

from the docs here, it does return a single row as result, but when i want to use the value of the array, i need to type it like this :

$data[0]['username']

instead of like this :

$data['username']

it does work as intended when i do it like this without the 'where' condition :

$data = $userModel->find(1);

but the problem arise when i want to search using the 'username' value instead. then i tried it like this and of course it doesn't work (return null) :

$data = $userModel->find('username', 'myname');

any pointer would be much apreciated, thank you.

Bharga Wiguna
  • 43
  • 1
  • 1
  • 7
  • 1
    if you wanna search engine you should change your query, find function works like that If no parameters are passed in, will return all rows in that model’s table, effectively acting like findAll(), though less explicit. so that your query is wrong for your expected output – Nurbek Boymurodov Sep 29 '20 at 09:09
  • 1
    ahh i see.. thank you for the explanation @NurbekBoymurodov – Bharga Wiguna Sep 30 '20 at 02:15

1 Answers1

4

Normally when you want more than one result you should use ->findAll(). When you just want one result its best to use ->first();

Find is there mostly if you just want one record by its primary key.

$user = $userModel->find($user_id);

However in the example you showed you're not passing a primary key, so it will assume that you want more than one result hence your array.

To make sure you only get one result and has the structure you want I would use:

$data = $userModel->where('username', 'myname')->first();

find = one row if primary key is passed or many rows if something else is used

findAll = always assumes the return of an array of results

first = always assume the return of one row

marcogmonteiro
  • 2,061
  • 1
  • 17
  • 26