简体   繁体   English

Laravel 隐藏枢轴数据

[英]laravel hide pivot data

How do I hide pivot column data when calling actors relational data the columns I want to hide when calling are "pivot" that contains "movie_id" and "person_id"如何在调用演员关系数据时隐藏数据透视列数据我想在调用时隐藏的列是包含“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');
    }
}

data returned:返回数据:

"actors": [
{
    "job_title": "Actor",
    "id": 1,
    "name": "Jaquan Nicolas",
    "profile_path": "asd",
    "pivot": {
        "movie_id": 1,
        "person_id": 1
    }
},

You need to define:您需要定义:

protected $hidden = ['pivot'];

On your App\\Person model, not your Movie model.在您的App\\Person模型上,而不是您的Movie模型。

Try to add this function into your model Movie尝试将此功能添加到您的模型电影中

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

Please write a function getActorAttributs() in your Model.php在您的 Model.php 中编写一个函数 getActorAttributs()
then write other one line in your model.php然后在你的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM