简体   繁体   中英

Many-to-Many duplicates

I'm working on a Laravel application and I have many to many relationship as follows:

I have authors table, writings table and author_writing table. The author_writing table has an extra field called role_id which contains the Id of the role the author had in that book such as, co-author, editor...etc. I want to get all the writings of an author and also all the roles of an author in a book: What i'm currently getting is this:

[
    {
        "id":1,
        "book_name": "xyz",
        .
        .
        .
        "pivot": {
            "writing_id": 4,
            "author_id": 4,
            "role_id": 1
        },
    },
    {
        "id":1,
        "book_name": "xyz",
        .
        .
        .
        "pivot": {
            "writing_id": 4,
            "author_id": 4,
            "role_id": 2
        },
    },
    {
        "id":1,
        "book_name": "xyz",
        .
        .
        .
        "pivot": {
            "writing_id": 4,
            "author_id": 4,
            "role_id": 4
        },
    },
] 

I'm getting this result by calling:

    public function writings(){
        return $this->belongsToMany(Writing::class, 'author_writing', 'author_id', 'writing_id')
        ->withPivot([
            'role_id' 
        ]);
    }

So the writing entries are duplicated because the author has more than one role, so if the author has three roles, then the same writing is shown three times, and the only difference is the role_id in the pivot. Hoe can show something like the following instead:

[
    {
        "id":1,
        "book_name": "xyz",
        .
        .
        .
        "pivot": {
            "writing_id": 4,
            "author_id": 4,
            "role_id": [1,2, 4]
        },
    },
]

So only one entry but the role_id contains all the roles the author has in a writing.

Try this:

public function writings(){
   return $this->belongsToMany(Writing::class, 'author_writing', 'author_id', 'writing_id')
    ->withPivot(['role_id'])
    ->selectRaw('DISTINCT Author.*, Author_Writing.*, Writing.*');
}

See an example here: https://laraveldaily.com/pivot-tables-and-many-to-many-relationships/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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