【问题标题】:Conditional Select Statement in laravel eloquentlaravel eloquent 中的条件选择语句
【发布时间】:2018-02-21 21:40:28
【问题描述】:

我有一个这样的原始查询

SELECT IF(`user_group` = '1', `total_score`, `score`) FROM `user`

现在我如何在laraveleloquent ORM 中转换这个查询

【问题讨论】:

  • 似乎是什么问题?你至少尝试过吗?
  • 我的问题是如何在 eloquent 中编写这个条件选择
  • 对这样的原始语句使用DB::raw(..)

标签: laravel laravel-4 eloquent


【解决方案1】:

将 MYSQL CASE 转换为 LARAVEL 查询

$query = DB::raw("(CASE WHEN user_group='1' THEN 'Admin' WHEN user_group='2' THEN 'User' ELSE 'Superadmin' END) as name");

然后简单地在

中执行这个查询
DB::table('tablename')->select($query)->get();

YourModelClass::select($query)->get();

你会得到结果。

【讨论】:

    【解决方案2】:
    DB::table('users')->select('IF(`user_group` = '1', `total_score`, `score`)')->get();
    

    这会起作用

    【讨论】:

      【解决方案3】:

      适用于需要条件连接并选择:

      使用 mysql 的原生条件可能是一个好方法。您可能会遇到这样的情况,如果 PHP 中的特定条件是真实的,那么您需要加入该表,否则不要加入。

      例如:

      如果 $loggedInUser 是管理员,那么您希望获得学生出勤率,否则只显示分数。

      你可以拥有(以下PS为伪代码,仅供参考):

      <?php 
      
      // Having the column selection only when a particular condition is true
      // Else have its value as NULL(You can have NA also)
      if($loggedInUser->role == 'admin'){
          $attendanceColumnSelect = DB::raw('attendance.total as total_attendance');
      }
      else{
          $attendanceColumnSelect = DB::raw('NULL as total_attendance');
      }
      // Students query with joins which must be there always
      $studentsQuery= Students::select('name', 'class', 'age', $attendanceColumnSelect)
                      ->join('someothertable', 'someothertable.student_id', '=', 'student.id');
      
      // Adding join of attendance only when required for admin role
      if($loggedInUser->role == 'admin'){
          $studentsQuery->join('attendance', 'attendance.student_id', '=', 'student.id');
      }
      // Getting final data
      $finalResult = $studentsQuery->get();
      
      ?>
      

      如果你尝试这样做:

      <?php 
      
      $finalResult = DB::select("
          SELECT  students.name, 
                  students.class, 
                  students.age, 
                  IF('$loggedInUser->role' = 'admin', attendance.total, NULL) as total_attendance
          FROM students
          INNER JOIN someothertable on someothertable.student_id = student.id
          INNER JOIN attendance on attendance.student_id = student.id
      ");
      ?>
      

      那么即使你知道条件为假,你也必须让出勤加入,否则它会出现“未知列出勤.total”错误。

      从我的角度来看,如果我们知道我们不需要特定列,我就不会加入该表。如果你对上面的原始查询做一个 EXPLAIN,你会发现即使 select 中的 If 条件为 false,MySQL 也需要出勤表。

      如果您发现此错误或任何更好的建议,请随时发表评论。

      【讨论】:

        猜你喜欢
        • 2021-10-26
        • 2015-08-19
        • 2013-10-04
        • 1970-01-01
        • 2014-11-20
        • 1970-01-01
        • 1970-01-01
        • 2011-04-22
        • 1970-01-01
        相关资源
        最近更新 更多