我有这个原始的mysql查询
SELECT campaign_influencers.*,
CASE influencer_status
WHEN 'PENDING' THEN 0
WHEN 'ACTIVE' THEN 1
WHEN 'LIVE' THEN 2
WHEN 'ACCEPTED' THEN 3
ELSE 5
end AS order_field
FROM campaign_influencers
WHERE campaign_id = 612
ORDER BY order_field
如何将其转换为雄辩的查询构建器?
这是我到目前为止所做的。
$sql = "SELECT campaign_influencers.*,
CASE influencer_status
WHEN 'PENDING' THEN 3
WHEN 'ACTIVE' THEN 1
WHEN 'LIVE' THEN 2
WHEN 'ACCEPTED' THEN 0
ELSE 5
end AS order_field
FROM campaign_influencers
WHERE campaign_id = :campaignId
ORDER BY order_field";
$campaignInfluencers = DB::select( DB::raw($sql), array(
'campaignId' => $id
));
唯一的问题是关系对象消失了。
foreach ($campaignInfluencers as $campaignInfluencer) {
$user = $campaignInfluencer->user; //will not work
}
答案 0 :(得分:1)
使用此:
CampaignInfluencer::select('*', DB::raw('CAST influencer_status ... AS order_field'))
->where('campaign_id', $campaign_id)
->orderBy('order_field')
->get();
答案 1 :(得分:0)
您可以使用FIND_IN_SET
SELECT campaign_influencers.*,
FIND_IN_SET(influencer_status,'ACCEPTED,LIVE,ACTIVE,PENDING') AS order_field
FROM campaign_influencers
WHERE campaign_id = 612
ORDER BY order_field DESC
使用eloquent作为@Jonas Staudenmeir已经建议你需要对原始sql表达式使用raw
方法
YourModel::select('*', DB::raw("FIND_IN_SET(influencer_status,'ACCEPTED,LIVE,ACTIVE,PENDING') AS order_field"))
->where('campaign_id', 612)
->orderBy('order_field', 'desc')
->get();