【问题标题】:Eloquent select rows with empty string or null value雄辩的选择具有空字符串或空值的行
【发布时间】:2014-01-09 12:11:05
【问题描述】:

我有类似$user->albums()->where('col', NULL) 的东西,它工作正常,然后我尝试使用$user->albums()->where('col', NULL)->or_where('col', '') 将其扩展为空字符串,但它不起作用。

我还看到on this post 我可以使用where_null('col'),但它不起作用和it's not documented。任何简单的方法来选择哪里为空或 NULL col

【问题讨论】:

标签: php orm relationship eloquent


【解决方案1】:

试试这个查询:

$users = DB::table('users')
        ->whereRaw('col = "" OR col IS NULL')
        ->get();

【讨论】:

    【解决方案2】:

    这个怎么样:

    $user->albums()->whereRaw("NOT col > ''")
    

    这样你可以同时检查两个条件

    【讨论】:

      【解决方案3】:

      尝试在第二个子句中使用orWhereNull

      $users = DB::table('users')
              ->where('col', '=', '')
              ->orWhereNull('col')
              ->get();
      

      【讨论】:

      • 如果我们有多个条件,我们将如何更改 where 函数?
      • @Nevermore 使用闭包:DB::table('users')->where(function($query) { $query->where(...)->orWhere(...)->orWhere(...); })->where(...)->where(...)->get();。这将在呈现的 SQL 中将基于闭包的条件封装在括号内。
      • 添加模型作用域方法可以使使用闭包更容易:用法:$model->whereIsEmpty($column1)->whereIsEmpty($column2);实现: public function scopeWhereIsEmpty($query, $column) { return $query->where( function ($query) use ($column) { $query->where($column, '')->orWhereNull($column) ; } ); }
      【解决方案4】:

      不确定,但这可能有效:

      $user->albums()->where_in('col', array(NULL,''));
      

      【讨论】:

      • NULL 无法使用 = 运算符进行比较,因此这不起作用。此外,该方法的名称是whereIn,而不是where_in。可以测试它,而不是写“不确定,但这可能有效”……
      • @jsphpl 您的评论当然是正确的,但应该注意的是,如果您在 Collection 对象而不是查询构建器上运行 whereIn('col', [null, '']),它工作。示例:$user->albums->whereIn('col', [null,'']);。注意使用神奇的关系属性albums,它返回一个集合,而不是albums(),它返回一个查询构建器实例。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-30
      • 1970-01-01
      相关资源
      最近更新 更多