简体   繁体   中英

How can Laravel / Eloquent's hasMany relationship have a local key?

In laravel, when a single entry in table A (eg Users) is associated with many entries in table B (eg Payment Methods), we define a "has many" relationship.

So, in User.php model we set:

return $this->hasMany('PaymentMethods', 'foreign_key', 'local_key');

The foreign key makes sense, eg it could be userid , because each entry in the payment methods table B will have only 1 user. However, why can a local key be set here? How can the users table ever have a "payment method" id key when it is associated with many payment methods, and therefore cannot be set to a single payment method id?

Similarly, to complete the relationship, I have to define a belongsTo in the PaymentMethod.php model:

 return $this->belongsTo('User');

In here, should one only set the second parameter, ie the local key (eg to userid )?

You can define local_key if the relationship is based on a different column than the primary key of User.

If you stick with the default, primary keys are named id and referring columns for example user_id . Then you can simply do:

return $this->hasMany('PaymentMethod');

and

return $this->belongsTo('User');

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