简体   繁体   中英

Using pivot model data as a relationship to another model in Laravel 4's Eloquent

I have a pivot table for a many to many relationship which includes a third index parameter for another model. I would like to be able to use Eloquent to access this model.

In my application, I have a User who can have many Subjects and many Semesters . When a user has a Subject , it needs to belong to a given Semester as well. I have a users , subjects and semesters table, as well as a subject_user table (which has user_id , subject_id and semester_id ).

When I retrieve the User 's subjects, I would also like to be able to get the Session the Subject has been connected to through the pivot table.

class User
{
    public function subjects()
    {
        $this->belongsToMany('Subject')->withPivot('session_id');
    }
}

What I would like to be able to do is as follows, and have the Session model available to me.

$user->subjects()->pivot->semester;

Is such a thing possible, or will this require an extension to Eloquent?

There is a way to do this by creating a class that extends Illuminate\\Database\\Eloquent\\Relations\\Pivot . Though this approach also requires adding some code to the two models that own this pivot so that they use the new Pivot when needed.

This link discusses the implementation of the Custom Pivot Model: https://github.com/laravel/framework/issues/2093#issuecomment-39154456

use Illuminate\Database\Eloquent\Relations\Pivot;

class SubjectUser extends Pivot {
   // add your relationships back to User and Subject
    public function session() {
         // your relation to session here
    }
}

class Subject extends Eloquent {
    ...
    public function newPivot(Eloquent $parent, array $attributes, $table, $exists) {
        if ($parent instanceof User) {
            return new SubjectUser($parent, $attributes, $table, $exists);
        }
        return parent::newPivot($parent, $attributes, $table, $exists);
    }
}

class User extends Eloquent {
    ...
    public function newPivot(Eloquent $parent, array $attributes, $table, $exists) {
        if ($parent instanceof Subject) {
            return new SubjectUser($parent, $attributes, $table, $exists);
        }
        return parent::newPivot($parent, $attributes, $table, $exists);
    }
}

Now you will have access to that pivot's relationship that have been defined.

$user->subjects->first()->pivot->session->...

Note: You will not be interacting with this class directly. It is created instead of the default Pivot when the pivot is needed between those 2 models.

Laravel Doc Reference: Working with Pivot Tables has a short passage about Defining a Custom Pivot Model.

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