你怎么能在laravel中做这个查询?

时间:2015-12-10 02:19:52

标签: 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_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

1 个答案:

答案 0 :(得分:0)

假设您有一个与表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 ...');