2016-11-15 84 views
0

我有以下MySQL查询,它提取最后9位作者的列表以撰写帖子,并按他们写的最后一篇文章的日期顺序列出它们。将原始查询转换为Laravel查询生成器

它工作正常,但我想用Laravel查询生成器重新编写它。这里是目前查询:

$authors = DB::select(" 
     SELECT 
      `a`.`id`, 
      `a`.`name`, 
      `a`.`avatar`, 
      `a`.`slug` AS `author_slug`, 
      `p`.`subheading`, 
      `p`.`title`, 
      `p`.`slug` AS `post_slug`, 
      `p`.`summary`, 
      `p`.`published_at` 
     FROM 
      `authors` AS `a` 
     JOIN 
      `posts` AS `p` 
      ON `p`.`id` = 
       (
       SELECT `p2`.`id` 
       FROM `posts` AS `p2` 
       WHERE `p2`.`author_id` = `a`.`id` 
       ORDER BY `p2`.`published_at` DESC 
       LIMIT 1 
      ) 
     WHERE 
      `a`.`online` = 1 
     ORDER BY 
      `published_at` DESC 
     LIMIT 9 
    "); 

我了解使用查询生成器的基础知识,但似乎没有要在Laravel文档任何允许我JOINON一个SELECT

任何人都可以提出一种方法,我可以使用Laravel查询构建器编写此查询,或者可能提出一种方法,我可以重写此查询以使查询构建器更容易构建?

回答

1

尝试做这样的

$data = DB::table('authors') 
     ->select(
      'a.id', 
      'a.name', 
      'a.avatar', 
      'a.slug AS author_slug', 
      'p.subheading', 
      'p.title', 
      'p.slug AS post_slug', 
      'p.summary', 
      p.published_at') 
     ->from('authors AS a') 
     ->join('posts AS p', 'p.id', '=', DB::raw(" 
      (
       SELECT p2.id FROM posts AS p2 
       WHERE p2.author_id = b.id 
       ORDER BY p2.published_at 
       DESC LIMIT 1 
      )")) 
     ->where('a.online', 1) 
     ->limit(9) 
     ->orderBy('p.published_at', 'desc') 
     ->get(); 
+0

谢谢,@Komal。你的回复给了我解决这个问题的正确想法。虽然你的答案有一些小错误。您是否介意在我将答案标记为正确之前先编辑它们? – Joseph

+0

ya..sure ..这是我的荣幸..并感谢:) – Komal

+0

好的,完成了。再次感谢! – Joseph