【问题标题】: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');
【解决方案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();