2015-11-17 48 views
0

在Laravel 4.2中,以下Eloquent查詢將刪除數組中指定的屬性。我想做一個類似的操作,在這個操作中我默認排除所有的屬性,只包含數組中的屬性。我怎樣才能做到這一點?我懷疑這個答案可能與在運行查詢之前在模型上定義一個自定義的$ appends數組有關,但我不知道該怎麼做。排除查詢中除指定屬性以外的所有屬性 - Eloquent Laravel 4.2

return MyModel::all()->each(function($row) { 
    $row->setHidden([ 
     'attribute_1', 
     'attribute_2' 
    ]); 
}); 

回答

1

在模型中

protected $excludedColumns = ['attr1', 'attr2']; 

    public function scopeExcludeColumns($query) { 
     return $query->select(array_diff(Schema::getColumnListing($this->table), $this->excludedColumns)); 
    } 

用途:

$result = Model::excludedColumns()->all(); 

另一種選擇是在模型建立$隱藏屬性由如下因素

protected $hidden = array('attr1','attr2'); 

但它會排除該只有在撥打電話時才能從模型中調用字段或$result->toJson();

相關問題