We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Query Builder join access joined models

Hi there,

I have kind of a problem.

In some cases, I opt to avoid lazy loading. In those cases I just use the query builder to directly join those.

So my question is: How can I access the joined models ?

Image that we are in the robot model. this model has:

$this->hasMany("id", "Models\Item", "robotId", array('alias' => 'items'));

and my item model has

$this->hasOne("itemId", "Models\RawItem", "id", array('alias' => 'rawItem'));

So in my robot model I just write a function:

public function getItemsEquipped() {
        return $this->modelsManager->createBuilder()
                                   ->from('Models\Item')
                                   ->join('Models\RawItem')
                                   ->where('isEquipped = 1')
                                   ->andWhere('robotId = :rid:')
                                   ->getQuery()
                                   ->execute(array('rid' => $this->id));
    }

Everything works fine so far BUT how can I access the joined RawItem ?

If I try to use $itemsReturned[0]->rawItem, it executes the hasOne relation and queries the table once again.

Hope my description makes sense and that somebody has an awnser to that :)

Greetings

edited Jul '15

This way:

return $this->modelsManager->createBuilder()
                                   ->from(['i' => 'Models\Item.*', 'r' => 'Models\RawItem.*'])
                                   ->from('Models\Item')
                                   ->join('Models\RawItem')
                                   ->where('isEquipped = 1')
                                   ->andWhere('robotId = :rid:')
                                   ->getQuery()
                                   ->execute(array('rid' => $this->id));
foreach ($result as $row) {
    echo $row->i->something; // Models\Item
    echo $row->r->something; // Models\RawItem
}


3.2k

So this is an error right ? the second from would override the first one (when using addFrom) I would guess.

Did you mean ->columns for the first one ? But that doesn't work either :(