Php 集合的where子句始终返回空
我有一个模型Php 集合的where子句始终返回空,php,laravel,laravel-5,Php,Laravel,Laravel 5,我有一个模型Images,它可以提取属性,例如hidden,它总是1或0 我试过: 但它总是返回0 但是,如果我使用SQLite对数据库进行原始查询: 17行在0毫秒内从中返回:选择*fromimagesWHEREhidden=“0”all将执行查询并返回一个集合。改用 dd([ Image::where('hidden', "0")->count(), Image::where('hidden', 1)->count(), ]);
Images
,它可以提取属性,例如hidden
,它总是1
或0
我试过:
但它总是返回0
但是,如果我使用SQLite对数据库进行原始查询:
17行在0毫秒内从中返回:选择*from
imagesWHERE
hidden=“0”代码>all
将执行查询并返回一个集合。改用
dd([
Image::where('hidden', "0")->count(),
Image::where('hidden', 1)->count(),
]);
如果必须使用集合,请执行以下操作:
dd([
$allImages->filter(function ($value) { return $value->hidden == 0; })->count(),
$allImages->filter(function ($value) { return $value->hidden == 1; })->count()
]);
不确定集合的where是否适用于对象。您正在对集合而不是查询生成器调用->where(…)
// This line will return a collection - https://laravel.com/docs/5.4/eloquent-collections
$all_images = Image::all();
如果您不需要可见和隐藏图像
// Collection does not have a method where(..)
// To get images that are "hidden" do this:
$hidden = Image::where('hidden', 0)->get(); // Again the result will be a collection
// To get images that aren't hidden do this:
$visible = Image::where('hidden', 1)->get(); // Will result in a collection
// If you need both visible and hidden you could load them all at once:
$images = Image::get();
// Then separate them with collection()->filter() - https://laravel.com/docs/5.4/collections#method-filter
$hidden = $images->filter(function ($v, $k) {
return $images[$k]->hidden;
});
$visible = $images->filter(function ($v, $k) {
return !$images[$k]->hidden;
});
如果您同时需要可见和隐藏图像
// Collection does not have a method where(..)
// To get images that are "hidden" do this:
$hidden = Image::where('hidden', 0)->get(); // Again the result will be a collection
// To get images that aren't hidden do this:
$visible = Image::where('hidden', 1)->get(); // Will result in a collection
// If you need both visible and hidden you could load them all at once:
$images = Image::get();
// Then separate them with collection()->filter() - https://laravel.com/docs/5.4/collections#method-filter
$hidden = $images->filter(function ($v, $k) {
return $images[$k]->hidden;
});
$visible = $images->filter(function ($v, $k) {
return !$images[$k]->hidden;
});
集合类确实有一个where方法;哦对不起,我不知道。很好的发现。