Model troubles

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",

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()

    foreach($items as $item){


Also isnt it a waste of resources to ask for the every img of every item if i only want one whe i do find()?

well, while doing some futher testing i found out that foreach doesnt pass values by reference (i'm kinda new to php '-.-)

and i got my default img by calling getDefaultImg in the view which solves the problem

Still im not sure if getting every img per item is a waste of resources since im only using 1 and if it is, if theres any way to prevent it.

edited Oct '14


In model Item

public function initialize()
    $this->hasMany("id", "ItemImg", "item_id", [''alias" => "itemimg"]);

And in controller you can call it

$object = Item::findFirstById($id)
foreach( $object->itermimg as item){