[英]laravel hide pivot data
如何在調用演員關系數據時隱藏數據透視列數據我想在調用時隱藏的列是包含“movie_id”和“person_id”的“pivot”
class Movie extends Model
{
protected $table = 'movies';
protected $hidden = array('pivot'); // doesn't work
protected $fillable = [
'adult',
'tmdb_id',
'imdb_id',
'release_date',
'original_language',
'original_title',
'title',
'popularity',
'backdrop_path',
'poster_path',
'runtime',
'tagline',
'trailer',
'summary'
];
public function persons() {
return $this->belongsToMany('App\Person', 'movies_pivot', 'movie_id', 'person_id');
}
public function actors() {
return $this->persons()->wherePivot('job_title', '=', 'Actor')->select('movies_pivot.job_title', 'persons.id', 'persons.name', 'persons.profile_path');
}
}
返回數據:
"actors": [
{
"job_title": "Actor",
"id": 1,
"name": "Jaquan Nicolas",
"profile_path": "asd",
"pivot": {
"movie_id": 1,
"person_id": 1
}
},
您需要定義:
protected $hidden = ['pivot'];
在您的App\\Person
模型上,而不是您的Movie
模型。
嘗試將此功能添加到您的模型電影中
public function toArray()
{
$attributes = $this->attributesToArray();
$attributes = array_merge($attributes, $this->relationsToArray());
unset($attributes['pivot']);
return $attributes;
}
請在您的 Model.php 中編寫一個函數 getActorAttributs()
然后在你的model.php中寫另一行
protected $appends = ['actor']; <br/>
protected $hidden = ['actors']; <br/>
public function getActorAttributs() {
$persons = $this->persons;
$output = [];
foreach ($persons as $person) {
unset($person['pivot']);
$output[] = $person;
}
return $output;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.