【问题标题】:Laravel - Eloquent where with arrayLaravel - Eloquent where with array
【发布时间】:2020-07-09 08:58:20
【问题描述】:

我正在尝试根据文档执行此查询,但它返回错误 array_key_exists(): The first argument should be either a string or an integer

https://laravel.com/docs/5.8/queries#where-clauses

 $imagessize = $galleryObj->photos->where([
                ['gallery_id','=', $gallery->id],
                ['delete','=',0],
            ])->sum('filesize');

【问题讨论】:

    标签: arrays laravel eloquent where-clause


    【解决方案1】:

    where 方法不接受数组,如果你愿意,你应该使用 whereIn 方法:

    whereIn 方法验证给定列的值是否包含在给定数组中:

    例如:

    users = DB::table('users')
                    ->whereIn('id', [1, 2, 3])
                    ->get();
    

    这将返回 id 为 1,2 和 3 的用户。

    但在你的情况下,我认为你不需要那个。试试这个:

    $imagessize = $galleryObj->photos->where('gallery_id',$gallery->id)->where('delete', 0)->sum('filesize');
    

    【讨论】:

    • where子句不能接受数组是不正确的。
    【解决方案2】:

    你绝对可以将数组解析为 Laravel Eloquent 中的 where 方法。这个在官方文档here中直接引用。

    使用下面的语法当然可以:

    $where=array();
    $where[] = ['field_a', '=', 'a'];
    $where[] = ['field_b', '=', 'test'];
    $results = DB::table('your_table')->where($where)->get();
    

    $where=array();
    $where[] = ['field_a', '=', 'a'];
    $where[] = ['field_b', '=', 'test'];
    $results = YourModelName::where($where)->get();
    

    【讨论】:

      猜你喜欢
      • 2021-09-08
      • 2021-07-12
      • 1970-01-01
      • 2013-07-10
      • 1970-01-01
      • 1970-01-01
      • 2014-08-14
      • 2018-01-17
      • 2017-04-01
      相关资源
      最近更新 更多