How to check relationship existence in Yii2?

104 Views Asked by At

I have two models User and Post. While fetching the user's data I want to also check if the user has any posts and then only return posts with the user data in response other wise only return the user's details.

When I do this $user->posts for the user who does not have any posts it returns null which then throws an exception.

Do we have any function to check relationship existence in Yii2 while querying the model, just like we have in Laravel?

$userDetails = User::has('posts')->get();
2

There are 2 best solutions below

1
ravi On

$this->hasOne(testModel::class, ['telephone_id' => 'id']);

0
Romas Markovcinas On

Do not have any experience with Laravel, but based on your question I assume Lavarel will return empty array() in your example?

Yii2 will always return null if no relation rows were found, except for scalar relations. Common Yii2 way to check if model has related items:

if($model->posts !== null) {
    foreach($model->posts as $post) {
       /* Do something with the $post */
    }
}

Alternatively you can use scalar relation, something like:

public function getPostsCount() {
    return $this->hasMany(Posts::class, ['author' => 'id'])->count();
} // $model->postsCount will return count of user posts, 0 in case user does not have any posts

To me it would make more sense if $model->posts would return empty array() instead of null, with apparent benefit that !== null statement would not be required each time. However, I guess this is something you get used to while developing on Yii2.