我需要使用 Eloquent但不使用该 DB::table函数来执行以下查询。
SELECT a.name, a.type
FROM (
(
SELECT name, 'Customer' as `type`
FROM customers
)
UNION ALL
(
SELECT name, 'Supplier' as `type`
FROM suppliers
)) AS a
ORDER BY a.type ASC
LIMIT 20
到目前为止,我能够获得merge这两个结果,但我无法按别名a或limit结果排序。话虽这么说,这有效:
$a = Customers::select('name', DB::raw("'Customer' AS `type`"))->get();
$b = Suppliers::select('name', DB::raw("'Supplier' AS `type`"))->get();
$result = $a->merge($b);
但这并不$result = $a->merge($b)->limit(10);
我还尝试fromSub按如下方式使用该功能:
$result = Customers::selectRaw('a.name, a.type')->fromSub(function ($subquery) use ($a, $b)
{
$subquery->union($a)->union($b);
})->get();
并返回错误:
方法 Illuminate\Database\Eloquent\Collection::getBindings 不存在。
我还尝试在函数内部构建查询并且几乎可以正常工作,缺少(的只是将我与目标分开。
$result = Customers::selectRaw('a.name, a.type')->fromSub(function ($subquery)
{
$sql = "name, 'Customer' AS type FROM customers) ";
$sql .= ' UNION ALL ';
$sql .= "(SELECT name, 'Supplier' AS type FROM suppliers) ";
$subquery->select(DB::raw($sql));
}, 'a')->get();
这将返回 SQL 查询:
SELECT a.name, a.type FROM (SELECT name, 'Customer' AS type FROM customers) UNION ALL (SELECT name, 'Supplier' AS type FROM suppliers)) as `a`
但不幸的是,它缺少(after a.type FROM (,它应该是a.type FROM ((,我不知道如何添加额外的 '(`。
狐的传说