[英]How to hide relationship columns in laravel?
我有这样的声明:
App\User::with('client')->find(2)->makeHidden('client.phone_no');
我想隐藏关系中的某些列,但我不能用makeHidden()
,因为它只接受Model
的参数而不是关系。
如何从关系中隐藏一些列?
如果您不想通过将phone_no
添加到hidden
属性来隐藏所有请求的phone_no
,您可以执行以下操作:
$user = App\User::with('client')->find(2);
$user->client->makeHidden('phone_no');
return $user;
正如我在对原始问题的评论中所述:我也发现了这种方法。 我相信这应该是您想要更频繁地排除列时应该使用的方法。 如果您只想排除一次列,我的解决方案就足够了。
接受回调以修改查询。
$users = User::with(['client' => function($query) {
$query->select(['id', 'name']);
}])->find(2);
您还可以在客户端模型上定义默认隐藏属性
protected $hidden = ['phone_no'];
您可以在模型中创建scope
并将其应用于构建器
在模型中定义这些功能
protected function columns(){
return Schema::getColumnListing('clients');
}
public function scopeExclude($query, $value = array())
{
return $query->select( array_diff( $this->columns(), $value) );
}
现在在查询构建器中使用它
App\User::with(['client' => function($query){
$query->exclude(['phone_no']);
}])->find(2)
您可以隐藏查询结果中的列(不需要急切加载):
$user = User::find(2);
$user->client->makeHidden('phone_no');
或者你甚至没有从数据库中获取它:
$user = User::with('client:id,user_id,...' /* other columns except phone_no */)->find(2);
试试这个:
App\User::with(['client' => function($query){
$query->makeHidden('client.phone_no')
}])->find(2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.