Search code examples
phpcodeigniter-4

CodeIgniter 4 Models->find()


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.


Solution

  • 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