Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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?



84.1k
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