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 select columns in phalcon Model with relationship

I have model named User and UserPhoto, which is related in one user to many user photo

$this->hasMany("id", "UserPhoto", "user_id"); $this->belongsTo("user_id", "User", "id");

If I try

$userData = User::find();

foreach ($userData as $user) { $userPhotoAry = $user->UserPhoto; }

I am getting relational resultset, but i need only selected column from table.

So I tried this,

$userData = User::find(array("columns"=>"id,username"));

foreach ($userData as $user) { $userPhotoAry = $user->UserPhoto; }

I am getting $UserPhoto is undefined.

Is there any way to mention column in find query along with relationship?

edited May '20

If you specify specific columns, find() wil not return a Model, it will return just a simple object. Therefore the relationships don't get set up. There is documentation that mentions this but I can't find it right now.

Generally you're not saving any appreciable CPU cycles by specifying specific columns, so I don't bother. If you absolutely must only have those 2 columns, then rather than using the relationship, just do your own query:

foreach ($userData as $user) { 
    $userPhotoAry = UserPhoto::find(["user_id = :id:","bind"=>["id"=>$user->id]]);
}

That's basically what Phalcon does when you use a relationship, so you're not creating any additional queries.