Php 如何在子查询中使用雄辩的模型属性?

Php 如何在子查询中使用雄辩的模型属性?,php,laravel,laravel-5,eloquent,Php,Laravel,Laravel 5,Eloquent,我有两个表用户,帖子,我正试图根据最近帖子的日期来排序用户 但不幸的是,我找不到在子查询中使用用户模型的firebase_id的方法。我不想直接使用原始查询或DB,如果有可能使用Eloquent进行此类查询的话 如何使用用户模型的firebase_id作为子查询参数 以下是我的非工作代码,让我了解我尝试做什么: User::select'users.*',DB::raw从posts中选择MAXid,其中posts.firebase\u id=users.firebase\u id作为最近的发布日

我有两个表用户,帖子,我正试图根据最近帖子的日期来排序用户

但不幸的是,我找不到在子查询中使用用户模型的firebase_id的方法。我不想直接使用原始查询或DB,如果有可能使用Eloquent进行此类查询的话

如何使用用户模型的firebase_id作为子查询参数

以下是我的非工作代码,让我了解我尝试做什么:

User::select'users.*',DB::raw从posts中选择MAXid,其中posts.firebase\u id=users.firebase\u id作为最近的发布日期 ->其中有'posts',函数$q{ $q->withCount'comments'; } ->使用['posts'=>函数$q{ $q->withCount'comments' ->orderBy'created_at'、'ASC'; }] ->按“最近发布日期”、“描述”排序 ->得到;
您可以使用QueryBuilder和联接:

$users = DB::table('users')
    ->join('posts.firebase_id ', '=', 'users.firebase_id ')
    ->orderBy('posts.recent_post_date', 'DESC')
    ->get();
更新 你要求有口才。你可以在哪里做

您可以使用selectSub添加子查询

试试下面的方法

$recentPostQuery = Post::select('created_at')
    ->whereColumn('firebase_id', 'users.firebase_id')
    ->latest()
    ->limit(1)
    ->getQuery();

User::select('users.*')
    ->selectSub($recentPostQuery, '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();

你正在尝试做更多的事情:你需要得到那些带有评论的帖子。问题是如何对用户进行排序。。如果我可以运行子查询并按最近的发布日期排序,它将解决问题。谢谢@Giacomo M,这也是一个很好的方法,但我也想将子查询用于另一个目的。谢谢@chanafdo,这是我一直在寻找的。
$recentPostQuery = Post::select('created_at')
    ->whereColumn('firebase_id', 'users.firebase_id')
    ->latest()
    ->limit(1)
    ->getQuery();

User::select('users.*')
    ->selectSub($recentPostQuery, '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();