I always thought that all my queries run quite smoothly, but recently started fully looking at whats happening under the hood, and realized that joins are completely ignored.
Simple example. Every contact has a target user. Here I'm trying to load that contact with corresponding user in a single query.
class Contact extends \Phalcon\Mvc\Model
{
(...)
public function initialize()
{
$this->hasOne('target_id', 'User', 'user_id', array('alias' => 'Target'));
}
}
// And then...
$c = $this->di->getModelsManager()
->createBuilder()
->from('Contact')
->join('User')
->andWhere('owner_id = 22')
->getQuery()
->execute();
$cc = $c->getFirst();
echo $cc->getTarget()->getEmail();
This generates two queries - one for contact with the correct join and one for the user later on.
- SELECT
contact
.contact_id
,contact
.owner_id
,contact
.tagline
FROMcontact
INNER JOINuser
ONcontact
.target_id
=user
.user_id
WHEREcontact
.owner_id
= 22 - SELECT
user
.user_id
,user
.email
,user
.password
,user
.salt
,user
.name
,user
.verified
,user
.created_at
,user
.updated_at
,user
.deleted_at
FROMuser
WHEREuser
.user_id
= :0 LIMIT :2
Is this a bug, or am I doing it wrong? Surely a single query should suffice here.