如何在 Yii2 中检查关系是否存在?

问题描述 投票:0回答:2

我有两个模型 User 和 Post。在获取用户数据时,我还想检查用户是否有任何帖子,然后只返回带有用户数据的帖子作为响应,否则只返回用户的详细信息。

当我为没有任何帖子的用户执行此操作

$user->posts
时,它返回 null 然后抛出异常。

在查询模型时,我们是否有任何功能可以在 Yii2 中检查关系是否存在,就像在 Laravel 中一样?

$userDetails = User::has('posts')->get();
activerecord yii2 yii2-model
2个回答
0
投票

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


0
投票

没有任何 Laravel 经验,但根据您的问题,我假设 Lavarel 将在您的示例中返回空数组()?

如果没有找到关系行,Yii2 将始终返回 null,标量关系除外。 Yii2 检查模型是否有相关项的常用方法:

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

或者你可以使用标量关系,比如:

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

对我来说,如果 $model->posts 返回空 array() 而不是 null 会更有意义,明显的好处是 !== null 语句不会每次都需要。然而,我想这是你在 Yii2 上开发时习惯的东西。

© www.soinside.com 2019 - 2024. All rights reserved.