Basic Kohana ORM find records
-
27-10-2019 - |
Question
I want to fetch some rows from my databases using the default ORM that Kohana 3 has, but I'm not getting what I want :-)
In my Controller:
$comptes = ORM::factory('compte');
#$comptes->where('empresa_id', '=', 2)->find_all();
$comptes->find_all();
This Query returns 169411 rows in my SQL, but here returns nothing. Of course I can limit using where, limit, or whatever, but I'm experimenting the basics with Kohana.
This returns 1
$result = count($comptes);
In my model view:
<?php var_dump($comptes)?>
produces this:
object(Model_Compte)#16 (34) { ["_has_one":protected]=> array(0) { } ["_belongs_to":protected]=> array(0) { } ["_has_many":protected]=> array(0) { } ["_load_with":protected]=> array(0) { } ["_validation":protected]=> NULL ["_object":protected]=> array(14) { ["id"]=> NULL ["empresa_id"]=> NULL ["codi_compte"]=> NULL ["compte"]=> NULL ["tipus"]=> NULL ["saldo_deure"]=> NULL ["saldo_haver"]=> NULL ["saldo"]=> NULL ["nivell"]=> NULL ["ultim_moviment"]=> NULL ["client_id"]=> NULL...
So this is the model, but how I can get the fetched data?
Also in my view:
foreach ($comptes as $row)
{
echo "<p>$row->codi_compte</p>";
}
?>
But I don't get nothing ...
thanks!
EDIT
This doesn't work:
$comptes = ORM::factory('compte');
$comptes->find_all();
But this works $comptes = ORM::factory('compte')->find_all();
Why?
And this doesn't work:
$comptes = ORM::factory('compte');
$comptes->where('empresa_id', '=', 2)->find_all();
But again, this works:
$comptes = ORM::factory('compte')->where('empresa_id', '=', 2)->find_all();
This multi-lines examples are from Kohana Web
Solution
The correct syntax to get all the rows would be:
$comptes = ORM::factory('compte')->find_all();
Then to check if something has been loaded use $comptes->loaded()
(not count($comptes)
).
Edit:
To get rows using a where
statement, you would write:
$rows = ORM::factory('compte')->where('empresa_id', '=', 2)->find_all();
OTHER TIPS
$comptes = ORM::factory('compte');
$comptes->find_all();
This doesnt work because you didn't assign find_all() result in a variables. You should write :
$comptes = ORM::factory('compte');
$rows = $comptes->find_all();
If you just want to break it down into multiple lines for readability's sake, this is the simplest method IMO...
Example:
$comptes = ORM::factory('compte')
->where('empresa_id', '=', 2)
->find_all();
$comptes = ORM::factory('compte');
$comptes->find_all();
This doesn't work because you use semicolon. semicolon means end of statement.
It will work fine if you erase semicolon like this:
$comptes = ORM::factory('compte')
->find_all();
Or make it as 1 line only:
$comptes = ORM::factory('compte')->find_all();