douqingnao9246 2014-11-10 09:57
浏览 54
已采纳

Laravel / Eloquent有多少关系有本地密钥?

In laravel, when a single entry in table A (e.g. Users) is associated with many entries in table B (e.g. 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, e.g. 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, i.e. the local key (e.g. to userid)?

  • 写回答

1条回答 默认 最新

  • duanhui5344 2014-11-10 10:30
    关注

    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');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?