返回
在 Laravel 4.2 中排除查询中的所有未指定属性
php
2024-03-19 23:29:41
在 Laravel 4.2 中排除查询中的所有未指定属性
问题
在 Laravel 4.2 中,你可以使用 Eloquent 查询排除指定的属性。然而,如果你想默认排除所有属性,只包含数组中的属性,该如何操作?
解决方法
一种有效的解决方案是,为模型定义一个自定义的 $appends
数组。
步骤:
- 定义
$appends
数组
// App/Models/MyModel.php
protected $appends = ['only_these_attributes'];
将你希望在查询中包含的属性添加到 $appends
数组。
- 排除所有未指定属性
return MyModel::all()->without('only_these_attributes');
without()
方法将从查询中排除指定的属性。在这种情况下,我们排除所有未在 $appends
数组中指定且已自动添加的属性。
优点
- 轻松排除所有未指定属性,即使它们通常会被自动添加到查询中。
- 允许灵活指定查询中包含的属性。
注意
- 确保
$appends
数组中的属性都是模型中可填写的。 - 这种方法不会影响模型的默认可访问属性。要排除这些属性,请使用
setHidden()
方法。
代码示例
use Illuminate\Database\Eloquent\Model;
class MyModel extends Model
{
protected $appends = ['only_these_attributes'];
public function scopeWithoutAllExcept($query, array $attributes)
{
return $query->without(array_diff($this->getFillable(), $attributes));
}
}
// 使用
$models = MyModel::withoutAllExcept(['name', 'email']);
常见问题解答
- 为什么需要自定义
$appends
数组?
自定义 $appends
数组允许你默认排除所有未指定属性,从而提供更大的灵活性。
withoutAllExcept()
方法有什么作用?
它从查询中排除所有未在指定数组中指定的属性,同时保留模型中可填写的属性。
- 这种方法的缺点是什么?
如果你需要排除模型的默认可访问属性,则需要使用 setHidden()
方法。
- 如何使用
withoutAllExcept()
方法?
只需在模型上调用它,并传递一个包含要包含的属性的数组即可。
- 这种方法可以提高性能吗?
是的,它可以通过排除不必要的属性来提高性能。