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 use found id in another query?

My goal is to find average by every user's id in the system so what I do first is, that I try to find all users:

$find = User::find();

later I try to pass that to function:

    return $this->getDi()->getShared('db')->query("SELECT AVG(r.rating) FROM system.user_rating r
        LEFT JOIN system.user u ON u.id = r.user_id
        WHERE u.id =':id:'",
        [
            'id' => $find->id
        ])->fetch();

But I get error:

Undefined property: Phalcon\Mvc\Model\Resultset\Simple::$id



43.9k
Accepted
answer

Hi,

$find is a resultset object comming from "$find = User::find();" <=> you'll get all the users

but your query:


 return $this->getDi()->getShared('db')->query("SELECT AVG(r.rating) FROM system.user_rating r
        LEFT JOIN system.user u ON u.id = r.user_id
        WHERE u.id =':id:'",
        [
            'id' => $find->id
        ])->fetch();

assume that there is a single object $find with an unique id (because of $find->id in the query, wich assume there there is a Phalcon\Mvc\Mode\Resultset\Simple object in $find object).

So, you shall use a foreach loop and build the response by your own (as an array or an object), something like:


$response = [];
$find = User::find();
foreach ($find as $user){
    $response[$user->id] = $this->getDi()->getShared('db')->query("SELECT AVG(r.rating) FROM system.user_rating r
        LEFT JOIN system.user u ON u.id = r.user_id
        WHERE u.id =':id:'",
        [
            'id' => $user->id
        ])->fetch();
}
return $response;

I've seen that you have posted some questions regarding that average calculation ....

You should better provide us for better understanding and better help from the community your model definition (and their relations) and what exactly your goal is.

Cheers.

edited Jan '18

Super, thank you :D