CodeIgniter 4 Models->find()

孤人 提交于 2021-01-05 07:51:06

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/64116186/codeigniter-4-models-find

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!