Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5, Derived table in join clause?

I have this query:

SELECT * FROM blog
LEFT JOIN (
    SELECT blog_id, AVG(value) as blog_rating FROM blog_ratings
    GROUP BY (blog_id)
) T ON T.blog_id = blog.id;

I do not know how to write this with Eloquent.

For Example:

Blog::select("*")->leftJoin( /* Here goes derived table */ )->get()

How do I accomplish this?

like image 746
clzola Avatar asked May 17 '15 09:05

clzola


1 Answers

I'd personally just use the fluent query builder, try this out and see how it works out:

DB::table('blog')
  ->select('*')
  ->leftJoin(DB::raw('(SELECT blog_id, AVG(value) as blog_rating FROM blog_ratings
    GROUP BY (blog_id)
    ) as T'), function ($join) {
        $join->on ( 'T.blog_id', '=', 'blog.id' );
    })
  ->get();

You can always swap ->get() for ->toSql() to dump out the query and adjust if you see any mistakes.

like image 82
haakym Avatar answered Oct 21 '22 16:10

haakym