Sql 您如何在laravel中执行此查询?

Sql 您如何在laravel中执行此查询?,sql,laravel,laravel-5.1,Sql,Laravel,Laravel 5.1,目标是得到一个带有最后评论日期的帖子列表 select `posts`.*, `follow_posts`.`follower_id` as `pivot_follower_id`, `follow_posts`.`post_id` as `pivot_post_id`, `follow_posts`.`created_at` as `pivot_created_at`, `follow_posts`.`updated_at` as `pivot_upd

目标是得到一个带有最后评论日期的帖子列表

 select
    `posts`.*,
    `follow_posts`.`follower_id` as `pivot_follower_id`,
    `follow_posts`.`post_id` as `pivot_post_id`,
    `follow_posts`.`created_at` as `pivot_created_at`,
    `follow_posts`.`updated_at` as `pivot_updated_at`, (select max(updated_at) from `comments` where `commentable_id` = `posts`.`id`) as `comentario`
from 
    `posts`
inner join 
    `follow_posts` on `posts`.`id` = `follow_posts`.`post_id`
where 
    `follow_posts`.`follower_id` = '1' 
order by 
    `comentario` desc

假设您有一个名为
Post
的模型与表
posts
相关:

use App\Post;
...
$posts = Post::innerJoin('follow_posts', 'posts.id', '=', 'follow_posts.post_id')
             ->where('follow_posts.follower_id', '=', '1')
             ->orderBy('comentario', 'desc')
             ->select([
                 'follow_posts.follower_id as pivot_follower_id',
                 'follow_posts.post_id as pivot_post_id',
                 'follow_posts.created_at as pivot_created_at',
                 'follow_posts.updated_at as pivot_updated_at',
             ])->selectRaw('
                 (select max(updated_at) 
                  from comments
                  where commentable_id = posts.id) as comentario')
             ->get();
我认为您必须指定要从表
posts
中选择的所有列。事件如果您不需要这样做,它会更快(您可能不需要所有这些),并且您确切地知道自己在做什么

如果您不想像上面提到的那样构建它,您可以始终使用

$posts = DB::select('SELECT ...');

你有没有为你的
帖子
追随者
提供有说服力的模型?如果是这样,您可以设置一个
多对多
关系。是的,我有必要的模型和关系,但不知道如何将“Post”与表“comments”的最后一条注释联系起来。到目前为止,您尝试了什么?另外,您是否已将您的
帖子
-
评论
关系设置为
hasMany
morphMany
?同样,如果您打算在这个查询中使用雄辩,那么最好在您的问题中加入所有必要的关系方法,因为这有点误导。