[英]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.