如何在子查询中使用Eloquent模型属性?

时间:2019-08-14 15:29:17

标签: php laravel laravel-5 eloquent

我有两个表(usersposts),我正在尝试根据最近帖子的日期订购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();

2 个答案:

答案 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();