Laravel hasMany 和 belongsTo 参数

新手上路,请多包涵

我有一个表存储,并且存储有很多库,在库中我有存储的外键 store_id

存储表

id(PK)

图书馆表

id(PK)
store_id(FK)

我对 hasManybelongsTo 参数感到困惑,在 文档 中它说

return $this->hasMany(‘App\Comment’, ‘foreign_key’);

return $this->hasMany(‘App\Comment’, ‘foreign_key’, ‘local_key’);

return $this->belongsTo(‘App\Post’, ‘foreign_key’, ‘other_key’);

hasMany foreign_key 和 local_key 来自哪个表?与 belongsTo 一样,foreign_key 和 other_key 来自哪个表?

店铺型号

public function library(){
    return $this->hasMany('App\Library', 'what_foreign_key_should_be_here','what_other_key_should_be_here');
}

图书馆模型

public function stores(){
    return $this->belongsTo('App\Stores', 'what_foreign_key_should_be_here', 'what_other_key_should_be_here');
}

因为有时我将表的主键id更改为sid等其他名称,所以我总是想指定哪个是外键和主键

原文由 Naib Sorion 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 881
1 个回答

为了简化语法,将 return $this->hasMany('App\Comment', 'foreign_key', 'local_key'); 参数视为:

  1. 您要链接到的模型
  2. 链接回当前表的 id 列的外部表(您要链接的表)的列(除非您指定第三个参数,在这种情况下它将使用该参数)
  3. 应该使用的当前表的列 - 即如果您不希望另一个表的外键链接到当前表的 id

在您的情况下,因为您在 libraries 表中使用了 store_id ,所以您的生活很轻松。在您的 Store 模型中定义时,以下内容应该可以正常工作:

 public function libraries()
{
    return $this->hasMany('App\Library');
}

在后台,Laravel 会自动将 Store 表的 store_id id 链接到 --- 表 —eca675888c93f 的 — Library —52ac93f 的列

如果您想明确定义它,那么您可以这样做:

 public function libraries(){
    return $this->hasMany('App\Library', 'store_id','id');
}

  • 模型标准是单数函数返回belongsTo,而复数函数返回hasMany(即 $store->libraries() or $library->store() )。

原文由 James 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题