使用 Eloquent ORM 使用 with 模型关联查询,如何处理select不同模型的字段(字段名可能相同)
遇到一个问题,就是
articles
和article_comments
两个数据模型
现在要查出来某个用户的评论列表(列表包含 评论内容article_comments.content
、评论时间article_comments.created_at
、评论所属的文章articles.title
)。
我首先需要根据article_comments
中的user_id
查询出来对应的评论列表,然后根据评论列表中的article_id
,然后找到对应文章标题。
一. 关联模型(一对多)
articles
文章模型// 核心方法 public function comments() { return $this->hasMany('App\Models\ArticleComment')->orderBy('id', 'desc'); }
article_comments
评论模型// 核心方法 public function article() { return $this->belongsTo('App\Models\Article'); }
二. 获取某个用户的评论列表
采用关联模型with (一对多)
// DB操作,主要是想打印一下sql use Illuminate\Support\Facades\DB; public function comments($id) { $user = \App\User::find($id); if(empty($user)) { echo '用户不存在'; exit; } DB::connection()->enableQueryLog(); // 开启查询日志 $commentList = ArticleComment::with(['article'=>function($query){ // 采用闭包进行处理,select出来想要的字段,但是必须包含关联外键 id return $query->select('title as article_title', 'id'); }]) ->where('user_id', $id) // 这里select出来评论模型的字段,但是也必须要包含外键 article_id ->select('content', 'created_at','user_id','id','article_id') ->orderBy('id','desc') ->get(); // 这个地方可以打印sql,挺不错的,记录一下 foreach (DB::getQueryLog() as $sql) { dump($sql['query']); } dd($commentList); exit; }
最后注意:如果想要指定字段,使用
select
时,一定要写两个表的关联字段,不然是查不到关联关系的。
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: