Laravel5.5 根据关联模型的字段模糊查询

比如后台文章列表要根据文章内容模糊筛选:

$where1 = [];
$where2 = [];

// 查询条件:帖子内容
if ( !empty($content) ) {
    $where1 = $content;
}

$perPage = $request->input('per_num', 10);  // 每页页码
$data    = TopicReply::where($where2)
    ->whereHas('TRtoData', function($query) use ($where1){
        if ( !empty($where1) ) {
            $query->where('content', 'like', '%'.$where1.'%');
        }
    })
    ->with('TRtoData')
    ->orderBy('id', 'desc')
    ->paginate($perPage);

如果要带关联表里的字段成为查询条件,用whereHas,如果要带关联表的信息,再with一下就可以了!

发布了29 篇原创文章 · 获赞 43 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_34248133/article/details/93196780
今日推荐