简体   繁体   中英

Having an extra attribute (not pivot) in a manytomany relationship with Laravel

TL;DR

Using Laravel 5.6, I need to add a one-to-many relationship to a many-to-many relation.

I'd like to know if I need another relationship and how to do that if so. Or if I can use the existing pivot table with an extra attribute?

More details

与支点的多对多关系

This screenshot from my pivot table shows how I manage my connections (aka "friends"): when both contacts have accepted the connection, then the status equals 1. So far so good, the many-to-many relationship system in Laravel manages perfectly that and everything is working great.

But now, I want to add a "favorite" system to these connections and one user can add another user as a favorite contact, but this is obviously not necessarily a mutual feeling, and the situation could ends up in something like this:

具有支点和属性的多对多关系

Of course, the many-to-many relationship with two pivots doesn't return anything because the starred field doesn't have the same value on both records. When I update the second record to "1" as well, the relation is returned correctly.

Is there a way to use that very table using both a pivot ( status ) and a simple extra attribute ( starred ), or do I need another relationship set up elsewhere? (and how to do it the best way?)

create starrings table with following data

Schema::create('starrings', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id');
            $table->unsignedInteger('starred_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('starred_id')->references('id')->on('users')->onDelete('cascade');

        });

on your User model, add the following:

    public function starred(){
        return $this->hasMany('App\Starring','starred_id');
    }
    public function starrings(){
        return $this->hasMany('App\Starring','user_id');
    }

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