【问题标题】:How to make a conditional active record relationship in YiiYii中如何建立有条件的活动记录关系
【发布时间】:2017-02-10 08:13:08
【问题描述】:

我在 Yii api 中有 Post、Comment 和 User。查询帖子时,结果应该是帖子数据、发布帖子的用户以及该帖子的任何评论,以及发布评论的用户以及完整的用户数据。

Comment 表包含一个 created_by 字段,它是 User 表中的 user_id

要获得一个帖子,这里是控制器:

public function actionView($id){
    $post = Post::find()
        ->innerJoinWith('user')
        ->joinWith('comments')
        ->where(['{{post}}.id' => $id])
        ->asArray()
        ->one();
    return $post;
}

这会返回一个按 id 的帖子和任何评论。

获取所有帖子:

public function actionIndex(){
   $posts = Post::find()
     ->joinWith('user', $eager)
     ->joinWith('comments', $eager)
     ->orderBy('updated_at DESC')
     ->limit(self::MAX_ROWS)
     ->asArray()
     ->all();
  return $posts;
}

在 Post 模型中,Comment 关系是这样设置的:

public function getComments()
{
    return $this
      ->hasMany(Comment::className(), ['object_id' => 'id']);
}

因此,如果有评论,这将返回评论,但不是每个评论的用户的完整用户数据。所以我把这个添加到getComments()

      ->joinWith('user u2','u2.id = comment.created_by')

除了评论之外,它确实会返回用户数据,但现在 actionIndex() 只返回有评论的帖子。

我查看了this SO question,但没有找到解决方案。如何有条件地将 joinWith 仅包含在带有评论的帖子中?

【问题讨论】:

    标签: yii yii2


    【解决方案1】:

    我建议你使用->with() 而不是joinWith()

    public function actionIndex() {
        $posts = Post::find()
            ->with('user')
            ->with('comments')
            ->orderBy('updated_at DESC')
            ->limit(self::MAX_ROWS)
            ->asArray()
            ->all();
    
        return $posts;
    }
    

    这样,您只需使用您应该在 Post 模型类中声明的关系。之后,还要在 Post 模型类中的 comments 关系声明中添加 ->with()

    public function getComments() {
        return $this
            ->hasMany(Comment::className(), [
                'object_id' => 'id',
            ])
            ->with('user');
    }
    

    这样,你应该得到所有的帖子,用户和 cmets 以及他们自己的用户。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多