Laravel 5, Derived table in join clause?

本秂侑毒 提交于 2019-12-07 05:30:44

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/30285302/laravel-5-derived-table-in-join-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!