Laravel hasMany和belongsTo参数

Nai*_*ion 8 php mysql laravel eloquent

我有一个表存储,而且商店有很多库,在库中我有商店的外键store_id.

存储表

id(PK)
Run Code Online (Sandbox Code Playgroud)

图书馆表

id(PK)
store_id(FK)
Run Code Online (Sandbox Code Playgroud)

我说它在文档中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');
}
Run Code Online (Sandbox Code Playgroud)

图书馆模型

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

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

Jam*_*mes 13

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

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

在你的情况下,因为你已经store_idlibraries桌子上使用过,你已经让自己的生活变得轻松.在您的Store模型中定义时,以下应该可以正常工作:

public function libraries()
{
    return $this->hasMany('App\Library');
}
Run Code Online (Sandbox Code Playgroud)

在幕后,Laravel会自动idStore表格的store_id列链接到表格的列Library.

如果你想明确定义它,那么你会这样做:

public function libraries(){
    return $this->hasMany('App\Library', 'store_id','id');
}
Run Code Online (Sandbox Code Playgroud)
  • 模型标准是单个命名函数返回belongsTo,而复数函数返回hasMany(即.$store->libraries() or $library->store()).


Ken*_*eth 7

试试这个。有用。将此添加到您的模型。

图书馆模式

public function store()
    {
        return $this->belongsTo(Store::class, 'store_id', 'id');
    }
Run Code Online (Sandbox Code Playgroud)

店铺型号

 public function libraries()
    {
        return $this->hasMany(Library::class);
    }
Run Code Online (Sandbox Code Playgroud)

示例代码。

 $store = Store::find(1);
 dd($store->libraries);
Run Code Online (Sandbox Code Playgroud)

因为在这种情况下,商店有许多库,所以Store模型具有libraries()功能。有关此标准的更多信息,请参阅James回答的最后一行。