2017-02-20 27 views
0

我有一个模型Images其中拉的属性,如hidden将始终是10哪里收集的条款总是返回空

我已经试过:

$all_images = Image::all(); 
var_dump($all_images->first()->hidden); 
dd([ 
    $all_images->where('hidden', "0")->count(), 
    $all_images->where('hidden', 0)->count(), 
    $all_images->where('hidden', 1)->count(), 
    $all_images->where('hidden', "1")->count() 
]); 


/* output 
sController.php:219:string '1' (length=1) 
array:4 [▼ 
0 => 0 
1 => 0 
2 => 0 
3 => 0 
]*/ 

但它总是返回0。

但是,如果我用做原料查询数据库SQLite的:

17 rows returned in 0ms from: SELECT * FROM图像0​​隐藏= '0';

回答

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() 
]); 

不知道该集合的地方使用对象效果很好。

0

您对集合而不是查询构建器调用->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; 
}); 
+2

集合类确实有一个地方方法; https://laravel.com/api/5.3/Illuminate/Support/Collection.html#method_where – sisve

+0

哦。对不起,我不知道。很好的发现。 – devk