Well i have 2 tables one called item and another called item_img.
item has many item_imgs and item_img belongs to 1 item. Item_img has a column called default which is a boolean. If that img is true then thats the image that's going to appear when i'm listing every item.
when i execute $items=Item:find(), i get every item with every img that they have assosiated, now my question is how can i get the default img?
i could do it with a foreach item->itemImg but that doesnt seem so elegant; ive been trying to do
public function getDefaultImg()
{
return ItemImg::findFirst(
array("item_id = ?1 and default = ?2",
"bind"=>array(1=>$this->id,2=>1)));
}
but im not really sure how to check if i got the img im searching for because when i try to pass it on to the view by doing $this->view->items=$items
it just throws an eror saying Access to undefined property Item::img since i dont have the attribute img define in the model, when i add it to the model i still dont get the image.
img doesnt map to any column in my database thats why i didnt have it so im not really sure if its correct to leave it in my model.
heres my 2 models
class Item extends \Phalcon\Mvc\Model
{
public $id;
public $name;
public $price;
public $stock;
public $details;
public $last_modified;
public $created_at;
public function initialize()
{
$this->hasMany("id", "ItemImg", "item_id", array(
'foreignKey' => array(
'action' => Relation::ACTION_CASCADE
)
));
}
...
class ItemImg extends \Phalcon\Mvc\Model
{
public $item_id;
public $hash;
public $img_type;
public $route;
public $default;
public function initialize()
{
$this->belongsTo("item_id", "Item", "id");
}
}
heres the controller action
public function indexAction()
{
$items=Item::find();
foreach($items as $item){
$item->img=$item->getDefaultImg();
}
$this->view->items=$items;
}