Laravel 5, Derived table in join article?

I have this request:

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 don't know how to write this with Eloquent.

Example:

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

      

How to do it?

+3


source to share


1 answer


I would just use a fluent query builder, try this and see how it works:

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 change ->get()

to ->toSql()

to unload the request and adjust if you see any errors.

+5


source







All Articles