我试图转换使用多个连接的SQL查询,以便与laravel自己的系统一起使用。
原始和工作查询:
$link = $this->pdo->prepare(
"SELECT
affiliates.affiliate_id,
affiliate_details.firstname,
affiliate_details.lastname,
sum(case when affiliates.status = 'accept' then 1 else 0 end) as offers_active,
sum(case when affiliates.status = 'deny' then 1 else 0 end) as offers_deny,
sum(case when affiliates.status = 'pending' then 1 else 0 end) as offers_pending,
count(invoices_aff.invoice_id) as sales,
count(invoice_details.invoice_id) as refunds
FROM
affiliates
INNER JOIN
offers ON (offers.id = affiliates.offer_id and offers.vendor_id = :vendor_id)
INNER JOIN
user_details as affiliate_details ON (affiliate_details.user_id = affiliates.affiliate_id)
LEFT JOIN
invoices ON (invoices.offer_id = offers.id)
LEFT JOIN
invoices_aff ON (invoices_aff.invoice_id = invoices.invoice_id AND invoices_aff.affiliate_id = affiliates.affiliate_id)
LEFT JOIN
invoice_details ON (invoice_details.invoice_id = invoices_aff.invoice_id AND invoice_details.status = 'refunded')
GROUP BY
affiliates.affiliate_id
"
);
$link->execute(array('vendor_id' => Auth::user()->id));
转换为使用laravel:
$affiliates = DB::table('affiliates')
->select(
array(
'affiliates.affiliate_id',
'affiliate_details.firstname',
'affiliate_details.lastname',
DB::raw('sum(case when affiliates.status = "accept" then 1 else 0 end) as offers_active'),
DB::raw('sum(case when affiliates.status = "deny" then 1 else 0 end) as offers_deny'),
DB::raw('sum(case when affiliates.status = "pending" then 1 else 0 end) as offers_pending'),
DB::raw('count(invoices_aff.invoice_id) as sales'),
DB::raw('count(invoice_details.invoice_id) as refunds')
)
)
->join('offers', function($join)
{
$join->on('offers.id', '=', 'offers.vendor_id');
$join->on('offers.vendor_id', '=', DB::raw(Auth::user()->id));
})
->join('user_details as affiliate_details', 'affiliate_details.user_id', '=', 'affiliates.affiliate_id')
->leftJoin('invoices', 'invoices.offer_id', '=', 'offers.id')
->leftJoin('invoices_aff', function($join)
{
$join->on('invoices_aff.invoice_id', '=', 'invoices.invoice_id');
$join->on('invoices_aff.affiliate_id', '=', 'affiliates.affiliate_id');
})
->leftJoin('invoice_details', function($join){
$join->on('invoice_details.invoice_id', '=', 'invoices_aff.invoice_id');
$join->on('invoice_details.status', '=', DB::raw("'refunded'"));
})
->groupBy('affiliates.affiliate_id')
->get();
但它给了我0个结果。
我对Laravels查询构建器还不是很熟悉,但我已经非常正确地遵循了示例(至少在我自己的脑海中)并且我在这里看不到我的错误。
我的查询错在哪里了?
答案 0 :(得分:2)
第一次加入时出现了错误('要约')。应该是offers.id = affiliates.offer_id而不是offers.id = offers.vendor_id。
->join('offers', function($join)
{
$join->on('offers.id', '=', 'affiliates.offer_id');
$join->on('offers.vendor_id', '=', DB::raw(Auth::user()->id));
});