CodeIgniter Forums
Why does $userModel->find(null) return all rows like $userModel->findAll() - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Model-View-Controller (https://forum.codeigniter.com/forumdisplay.php?fid=10)
+--- Thread: Why does $userModel->find(null) return all rows like $userModel->findAll() (/showthread.php?tid=78868)



Why does $userModel->find(null) return all rows like $userModel->findAll() - sba - 03-20-2021

Let's say I have a table with users (id, firstname) and a table with pets (id, id_user, species, petname) and one model each representing the tables.
Now I query all users owning a cat:

$this->userModel = new UserModel();
$this->petModel  = new PetModel();

$cat_owner = $this->userModel->find(
    $this->petModel->where('species', 'cat')->findColumn('id_user')
);


There are cat owners - find() returns rows of all users owning a cat.

But no one holds an Iguana:
$iguana_owner = $this->userModel->find(
    $this->petModel->where('species', 'iguana')->findColumn('id_user')
);


Incorrectly, now we receive all users because $this->petModel->where('species', 'iguana')->findColumn('id_user') returns null and find() acts like findAll()

I know, the query could also be written using join or otherwise... but I don't understand why find(null) returns all rows, whats the idea behind it?

Or am I misunderstanding something about the models, what is the best practice?


RE: Why does $userModel->find(null) return all rows like $userModel->findAll() - kenjis - 03-20-2021

find(null) means no where clause.
So you get all records.


RE: Why does $userModel->find(null) return all rows like $userModel->findAll() - sba - 03-20-2021

(03-20-2021, 06:16 AM)kenjis Wrote: find(null) means no where clause.
So you get all records.

yes, this I understand, it's according the documentation.

But what's the idea behind this? Why does it return all records when I say find(null)?
this is semantically nonsense... search for nothing should return nothing and not all. This would be more logical for my understanding..

furthermore find([]) gives a runtime error (empty where clause)...

to chain model functions it would give IMHO shorter an more simple code if I not need to check first the array containing id(s) to use find()


RE: Why does $userModel->find(null) return all rows like $userModel->findAll() - kenjis - 03-20-2021

(03-20-2021, 06:45 AM)sba Wrote: But what's the idea behind this? Why does it return all records when I say find(null)?
this is semantically nonsense... search for nothing should return nothing and not all. This would be more logical for my understanding..

Well, you have a point.