我目前有一个SQL查询,这是一个出色的stackoverflow成员今天早些时候帮助我。目前它的工作方式非常好,而且我希望它能够正常工作。
唯一的问题是它的RAW SQL,我非常希望能够使用Laravel Query Builder。
抱歉这是编辑 - 这是原始的查询:
$addresses = DB::select(
DB::raw('
(SELECT
"Company" AS object_type_name,
companies.company_name AS object_name,
addresses.*
FROM
addresses
INNER JOIN
companies
ON
addresses.object_id = companies.id
WHERE
addresses.object_type = 2)
UNION ALL
(SELECT
"Job" AS object_type_name,
jobs.job_title AS object_name,
addresses.*
FROM
addresses
INNER JOIN
jobs
ON
addresses.object_id = jobs.id
WHERE
addresses.object_type = 4)
'));
这是我到目前为止的代码:
$bindings = array(
'soft_deleted' => 0,
'user' => 1,
'company' => 2,
'candidate' => 3,
'job' => 4,
);
$companies = DB::table('addresses')->select(
'addresses.*',
'companies.company_name as object_name'
)->where('addresses.soft_deleted', '=', 0)->join('companies', function($join) use ($bindings){
$join->on('addresses.object_id', '=', 'companies.id')
->where('addresses.object_type', '=', $bindings['company']);
});
$jobs = DB::table('addresses')->select(
'addresses.*',
'jobs.job_title as object_name'
)->join('jobs', function($join) use ($bindings){
$join->on('addresses.object_id', '=', 'jobs.id')
->where('addresses.object_type', '=', $bindings['job']);
});
$addresses = $companies->unionAll($jobs)->get();
使用上面的代码,我收到以下错误:
SQLSTATE [HY093]:无效的参数编号(SQL :(选择addresses
。,companies
。company_name
为object_name
来自addresses
内部在companies
上加入addresses
。object_id
= companies
。id
和addresses
。object_type
= 2其中addresses
。soft_deleted
= 0)联合全部(选择addresses
。,jobs
。job_title
为object_name
来自addresses
内部联接{ {1}} jobs
= addresses
。object_id
和jobs
。id
=?))
我已经做了几个小时的搜索,但我似乎找不到这个小问题的答案。
答案 0 :(得分:1)
我设法解决了这个问题。就像从每个连接闭包中删除->where
并将其链接到连接本身而不是嵌套它一样简单。
在:
$companies = DB::table('addresses')->select(
'addresses.*',
'companies.company_name as object_name'
)->where('addresses.soft_deleted', '=', 0)->join('companies', function($join) use ($bindings){
$join->on('addresses.object_id', '=', 'companies.id')
->where('addresses.object_type', '=', $bindings['company']);
});
$jobs = DB::table('addresses')->select(
'addresses.*',
'jobs.job_title as object_name'
)->join('jobs', function($join) use ($bindings){
$join->on('addresses.object_id', '=', 'jobs.id')
->where('addresses.object_type', '=', $bindings['job']);
});
后:
$companies = DB::table('addresses')->select(
'addresses.*',
'companies.company_name as object_name'
)->where('addresses.soft_deleted', '=', 0)->join('companies', function($join){
$join->on('addresses.object_id', '=', 'companies.id');
})->where('addresses.object_type', '=', 2);
$jobs = DB::table('addresses')->select(
'addresses.*',
'jobs.job_title as object_name'
)->where('addresses.soft_deleted', '=', 0)->join('jobs', function($join){
$join->on('addresses.object_id', '=', 'jobs.id');
})->where('addresses.object_type', '=', 4);
$addresses = $companies->unionAll($jobs)->get();
希望这有助于某人。