简体   繁体   中英

Should some relationship tables have their own models?

I'm writing an API with an MVC framework in PHP, and I'm using the Eloquent ORM.

My app has some models which are eventually linked through relationship tables, but intended to be created in a separate, decentralized manner.

Should these relationship tables have their own models, or should the models that are related have methods to create links?

With Eloquent, in regards to intermediate or pivot tables with many to many relationships, you shouldn't need to create an additional model.

You should always set up the relationships for related Models with the belongsToMany() method, documented here: https://laravel.com/docs/5.3/eloquent-relationships#many-to-many

class User extends Model
{
    /**
     * The roles that belong to the user.
     */
    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }
}

They have various methods of then using this relationship to adding or updating items to the pivot table including attach, detach, or sync documented here: https://laravel.com/docs/5.3/eloquent-relationships#updating-many-to-many-relationships

$user = App\User::find(1);
$user->roles()->attach($roleId);

You can also add data to extra fields:

$user->roles()->attach($roleId, ['expires' => $expires]);

Extra fields on the pivot table are important when you have data, like timestamps, that relate to the relationship and not either of the related models.

An example I could think of would be if you wanted to maintain a history of store managers. You wouldn't just want a store_id and manager_id, you'd also want a started_at and ended_at timestamp. This would allow you to view who is managing a store right now, but also who managed a store in the past.

With Eloquent, these types of extra fields don't require their own model, they can be accessed through the various methods documented above.

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