laravel hide pivot数据

时间:2017-01-24 18:16:55

标签: php laravel

如何在调用actor关系数据时隐藏数据透视表数据我想在调用时隐藏的列是包含“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
    }
},

3 个答案:

答案 0 :(得分:7)

您需要定义:

protected $hidden = ['pivot'];

在您的App\Person型号上,而不是您的Movie型号。

答案 1 :(得分:0)

尝试将此功能添加到模型电影

    public function toArray()
{
    $attributes = $this->attributesToArray();
    $attributes = array_merge($attributes, $this->relationsToArray());
    unset($attributes['pivot']);
    return $attributes;
}

答案 2 :(得分:0)

请在您的Model.php中编写函数getActorAttributs()
然后在模型中写另一行。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;
    }