Laravel 5, Derived table in join clause?
Asked Answered
T

1

8

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?

Talyah answered 17/5, 2015 at 9:17 Comment(0)
I
14

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.

Ingle answered 17/5, 2015 at 12:14 Comment(2)
Since I cannot use DB::table as it will not give me model (I have relations that are needed for representing data) I came up with this Blog::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();Talyah
learning that you can pass the raw derived table sql as the first argument to a *join function, rather than the table name, was clutchFleischer

© 2022 - 2024 — McMap. All rights reserved.