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

How to make this query with model relationships.

I have two tables, "users" and "products." To obtain all the products of a certain user, I use a "hasMany" relationship. How do I get a single record?

SELECT * FROM products WHERE product_id = x AND user_id = y LIMIT 1

edited Jul '19

You can do it in two ways:

  1. use findFirst() method

    $model->findFirst(['condtitions' => 'product_id = :x: AND user_id = :y:', 'bind' => [ 'x' => ...product id ..., 'y' => ... user id ... ]]);
  2. use find() method with limit argument:
    $model->find(['condtitions' => 'product_id = :x: AND user_id = :y:', 'bind' => [ 'x' => ...product id ..., 'y' => ... user id ... ], 'limit' => 1]);