Laravel Eloquent Select CASE?

时间:2013-06-13 16:19:28

标签: sql select laravel case eloquent

是否有任何有PHP和PHP经验的人Laravel Eloquent谁可以帮我解决这个问题?我正在尝试注入一个CASE ... WHEN .. END ...在raw()方法中。它似乎完全被忽略了。现有的文件还没有。我尝试了几种不同的东西,但没有占上风。我试图解决这个问题:

SELECT shares.id, ..., 
   CASE WHEN users.id = <CurrentUser> THEN 1 ELSE 0 END AS is_user, 
   ...
FROM <table>
...

源代码如下:

$shares = Share::where('shares.status', '=', SHARE_STATUS_APPROVED)
                    ->where('shares.deleted', '=', '0')
                    ->where('locations.lat', '<=', $nelat)
                    ->where('locations.lat', '>=', $swlat)
                    ->where('locations.lng', '>=', $nelng)
                    ->where('locations.lng', '<=',  $swlng)
                    ->where('users.id', '=',  $user)
                    ->orWhere('shares.connected_user_id', '=',  $user)
                    ->join('users', 'shares.user_id', '=', 'users.id')
                    ->join('locations', 'locations.id', '=', 'users.location_id')
                    ->join('provinces', 'provinces.id', '=', 'locations.province_id')
                    ->join('countries', 'countries.id', '=', 'locations.country_id')
                    ->select('shares.id AS share_id', 'users.id AS user_id', 'shares.connected_user_id', 'shares.original_language_id', 'shares.image',
                        'users.first_name', 'users.last_name', 'users.email',
                        'locations.city', 'provinces.name', 'countries.code',
                        'locations.lat', 'locations.lng',
                        'shares.created_at')
                    ->raw('(CASE WHEN users.id = ' . $user . ' THEN 1 ELSE 0 END) AS is_user')
                    ->orderBy('shares.created_at', 'desc')
                    ->orderBy('users.id', 'asc')
                    ->orderBy('shares.connected_user_id', 'asc')
                    ->get();

2 个答案:

答案 0 :(得分:47)

raw()声明中移动SELECT来电:

->select('shares.id AS share_id', 'users.id AS user_id', 'shares.connected_user_id',    
  'shares.original_language_id', 'shares.image',
  'users.first_name', 'users.last_name', 'users.email',
  'locations.city', 'provinces.name', 'countries.code',
  'locations.lat', 'locations.lng',
  'shares.created_at',
  DB::raw('(CASE WHEN users.id = ' . $user . ' THEN 1 ELSE 0 END) AS is_user')
  )
->orderBy('shares.created_at', 'desc')

来自:https://laravel.com/docs/5.4/queries#raw-expressions

答案 1 :(得分:5)

或者,您可以改为使用selectRaw

->selectRaw("shares.id AS share_id, users.id AS user_id , 
    shares.connected_user_id ,    
      shares.original_language_id, shares.image,
      users.first_name, users.last_name, users.email,
      locations.city, provinces.name, countries.code,
      locations.lat, locations.lng,
      shares.created_at,
      (CASE WHEN users.id = {$user} THEN 1 ELSE 0 END) AS is_user)")
    ->orderBy('shares.created_at', 'desc')