Laravel通过自定义字段发出雄辩的查询顺序

时间:2018-06-01 00:34:54

标签: laravel eloquent laravel-query-builder

我有这个原始的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
}

2 个答案:

答案 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();