我有SQL查询(请参见示例)。 但是我找不到如何在查询生成器中编写它的方法。 您有什么想法吗?
WITH main AS (
SELECT id FROM table1
)
SELECT * FROM table2
WHERE
table2.id IN (SELECT * FROM main)
我想要的格式如下:
$latestPosts = DB::table('posts')
->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
->where('is_published', true)
->groupBy('user_id');
$users = DB::table('users')
->joinSub($latestPosts, 'latest_posts', function ($join) {
$join->on('users.id', '=', 'latest_posts.user_id');
})->get();
但用于WITH
答案 0 :(得分:0)
Query builder has to be compatible with multiple database engines (mysql, postgresql, sql lite, sql server) and as such only offers support for common functionality.
Assuming your query returns data, you may be able to use the DB:select()
method to execute a raw query。
$data = DB::select('WITH main AS (SELECT id FROM table1), SELECT * FROM table2 WHERE table2.id IN (SELECT * FROM main)');
DB:select方法还接受第二个用于使用命名绑定的参数。
或者有laravel-cte之类的可用软件包,它们会将功能添加到Eloquent / Query Builder。
答案 1 :(得分:0)
Laravel不支持通用表表达式。
我为此创建了一个包:https://github.com/staudenmeir/laravel-cte
您可以像这样使用它:
$query = DB::table('table1')->select('id');
$result = DB::table('table2')
->withExpression('main', $query)
->whereIn('table2.id', DB::table('main')->select('id'))
->get();