在 Laravel 4.2 中,以下 Eloquent 查询将删除数组中指定的属性。我想做一个类似的操作,默认情况下排除所有属性,只包含数组中的属性。我怎样才能做到这一点?我怀疑答案可能与在运行查询之前在模型上定义自定义 $appends 数组有关,但我不知道如何执行此操作。
return MyModel::all()->each(function($row) {
$row->setHidden([
'attribute_1',
'attribute_2'
]);
});
在你的模型中
protected $excludedColumns = ['attr1', 'attr2'];
public function scopeExcludeColumns($query) {
return $query->select(array_diff(Schema::getColumnListing($this->table), $this->excludedColumns));
}
用途:
$result = Model::excludedColumns()->all();
另一个选项是通过以下方式在模型上设置 $hidden 属性
protected $hidden = array('attr1','attr2');
但仅当调用
$result->toArray;
或 $result->toJson();
时才会从模型中排除此字段