我有两个表(users
,posts
),我正在尝试根据最近帖子的日期订购users
。
但是不幸的是,我找不到在子查询中使用用户模型的firebase_id
的方法。如果可以使用Eloquent进行此类查询,我不想直接使用原始查询或DB。
如何使用用户模型的firebase_id
作为子查询参数?
这是我无法正常工作的代码,可让我对我想做的事情有所了解:
User::select('users.*', DB::raw("SELECT MAX(id) FROM posts WHERE posts.firebase_id = users.firebase_id as recent_post_date"))
->whereHas('posts', function ($q) {
$q->withCount('comments');
})
->with(['posts' => function ($q) {
$q->withCount('comments')
->orderBy('created_at', 'ASC');
}])
->orderBy('recent_post_date', 'DESC')
->get();
答案 0 :(得分:1)
您可以使用rm
添加子查询。
尝试以下
selectSub
答案 1 :(得分:0)
您可以使用QueryBuilder和联接:
$users = DB::table('users')
->join('posts.firebase_id ', '=', 'users.firebase_id ')
->orderBy('posts.recent_post_date', 'DESC')
->get();
更新
您要求雄辩。您可以使用whereHas
来做到这一点。
$users = User::whereHas('posts', function (Builder $query) {
$query->orderBy('posts.recent_post_date', 'DESC');
})->get();