2017-02-20 82 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