Search in ORM

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 I can use queryBuilder like that:

  • ->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

$users = Users::find(...something for Users...);

/*
* return array of Phalcon\Mvc\Model
*/
$users_with_active_posts = $users->filter(function($user) {
    if ($user->posts->active) {
        return $user;
    }
});

echo $users_with_active_posts[0]->name;


1.1k
edited Jul '15

I mean something other.

Is possible to create query like;

  • SELECT * FROM users u LEFT JOIN posts p ON u.id = p.iduser INNER JOIN bouns b ON u.id = b.iduser WHERE u.active = '1' AND b.curdate > '2015-02-21' ORDER BY u.id ASC, p.id ASC;

in ORM without query builder and executeQuery() ?

edited Jul '15

As i know, order by field of related model doesn't available in ORM.

So, without "ORDER BY p.id" your query can be created as i wrote earlier.

Otherwise I would have done so:

$builder = $this->getModelsManager()->createBuilder();
$builder
    ->addFrom("users", "u")
    ->innerJoin("bouns", "u.id = b.id_user", "b")
    ->leftJoin("posts", "u.id = p.id_user", "p")
    ->where("u.active = '1' AND b.curdate > '2015-02-21'")
    ->orderBy(["u.id ASC", "u.id ASC"])
    ->getQuery()
    ->execute();

\Phalcon\Mvc\Model::find() also uses QueryBuilder in its code.