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

Model relationships

Hello.

I was wondering if model relationships, using belongsTo, that it only fetches if there is a match

Let's say i pull all comments from the database. Every comment have a post_id

If this post_id retrives a row that dosent existst, it dosent fetch the comment either?



93.7k
Accepted
answer

No, model relations only make a request when you call the relation.

$comments  = CommentsModel::find(); // This fetches all your comments
foreach ($comments as $comment) {
    echo $comment->id; // Properties from Comments table
    echo $comment->post->title; // This way you access the posts table, because this comment belongsTo a post.
}

If the post does not exist it will NOT affect your comments query.

Okay thanks for your answer