我目前有一個SQL查詢,這是一個夢幻般的計算器成員今天早些時候幫助我的。目前,它的工作非常好,我希望它能夠工作。將參數綁定傳遞給Laravel查詢生成器?
唯一的問題是它的RAW SQL,我非常想使用Laravel查詢生成器來工作。
很抱歉,這是一個編輯 - 這裏是原始查詢:
$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
as object_name
from addresses
內部加入companies
對addresses
。 object_id
= companies
。 id
和addresses
。 object_type
= 2其中addresses
。 soft_deleted
= 0)UNION ALL(選擇addresses
。,jobs
。job_title
作爲object_name
從addresses
內對addresses
加入jobs
。object_id
= jobs
。id
和addresses
。object_type
=?))
我已經做了搜索的價值小時但我似乎無法找到這個小問題的答案。
瘋狂的猜測:第一個'select'會改變你的'$ bindings'。爲了排除這種情況,我會在每次select之後轉儲'$ bindings'。 – 2015-04-01 00:01:29