Is it true that if I have a table:
entry id | crop id | price
1 | 3 | 90.00
2 | 3 |100.00
With this code: if $crop_id = 3
$price=Price::model()->find('crop_id = :cropId', array(
':cropId' => $cropId
) );
It only returns the field of the first row. 1 | 3 | 90.00
With this code:
$price=Price::model()->findAll('crop_id = :cropId', array(
':cropId' => $cropId
) );
It returns all the field of the crop_id = 3
thus returning 1 | 3 | 90.00 and 2 | 3 | 100.00
If it is true, how can I price[0] or price[1]?? Because it spouts an error.
Yes, it’s true. Find returns one record, and findAll returns array of records.
So you can do $items = findAll(…) and then use $items[0] etc.
I have no idea why you’re getting the error. Maybe the result was empty or null.
You can use print_r to see what has happened.
redguy
(Maciej Lizewski)
October 13, 2012, 5:20pm
3
actually findAll can return associative array with key values equal to some field passed as ‘index’ in criteria object. If so - ‘0’ and ‘1’ can be invalid array keys. you should print_r($price) to check what exactly is returned or use safe iteration like:
foreach( $price as $p ) {}
_uJJwAL
(_uJJwAL_)
October 15, 2012, 5:51am
4
$price=Price::model()->findAll('crop_id = :cropId', array(
':cropId' => $cropId
) );
If you do this then, you can obtain result as such.
foreach($price as $object) {
echo $object -> entry_id;
}
if you need in an array with index 0, 1. you can push it in an array within foreach loop.
$entryID = array();
foreach($price as $object) {
array_push($entryID, $object->entry_id);
}
Now you have your entry id in an array with index 0, 1 …
Try It!
Hi,
Not that I have anything to add to this just would like to say thank you for giving this information as it helped me with a related problem.
try to use foreach to loop through…
foreach($product as $products)
{
}
//example would be
$product =Product::model()->findAll();
$productsArray = array();
foreach($product as $products)
{
$productsArray[] = array(
'id' => $products->id,
'name' => $products->name,
'description' => $products->description,
);
}
you can loop through like this…
hope this helps…
Thanks,