mtoy
mtoy

Reputation: 195

Phalcon - search with joins

I have 2 models: - models/Users.php - models/Posts.php

Users has:

$this->hasMany('id', 'Posts', 'id_user');

Posts has:

$this->belongsTo('id_user', 'Users', 'id');

and this is fine.

Is possible to create search using phalcon ORM ?

I know that I can do this (with leftjoin, innerjoin, etc) like that:

$this->modelsManager->executeQuery($sql_with_joins, $bind_array);

or use queryBuilder like:

...
->columns('id, name')
->from('Users')
->join('Posts)
...
->orderBy('name')

But how can I create search with ORM construction:

Users::find( .. here join and search on Posts model fields .. )->toArray();

Thanks for advance

Upvotes: 1

Views: 1509

Answers (1)

yergo
yergo

Reputation: 4980

You should use queryBuilder for best performance. Anyway if you alias your relation and stick to objects rather than arrays youre able to make some tricks like:

// in users model
$this->belongsTo(
    'id',   // local id
    'Posts', // model relation
    'user_id', [ // related id
        'alias' => 'posts' // alias for related records
    ]
);

$user = Users::findFirst(); // first user from table, just for example

// foreach($user->posts as $post) // using exact alias name
foreach($user->getPosts() as $post) { // using getter for alias
    var_dump($post);
}

Thing is, for more users in such case, like when foreaching over users and than foreaching over posts, engine is sending separate query what may stress server quite alot, depending on situation. Here you have a bit more in topic.

Upvotes: 1

Related Questions