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

家住魔仙堡 提交于 2019-12-19 10:45:28

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/17367440/using-pivot-model-data-as-a-relationship-to-another-model-in-laravel-4s-eloquen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!