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)
我说它在文档中hasMany
与belongsTo
参数包含相混淆
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');
参数视为:
id
当前表的列的外表(要链接的表)的列(除非您指定第三个参数,在这种情况下它将使用它)id
当前表的列在你的情况下,因为你已经store_id
在libraries
桌子上使用过,你已经让自己的生活变得轻松.在您的Store
模型中定义时,以下应该可以正常工作:
public function libraries()
{
return $this->hasMany('App\Library');
}
Run Code Online (Sandbox Code Playgroud)
在幕后,Laravel会自动id
将Store
表格的store_id
列链接到表格的列Library
.
如果你想明确定义它,那么你会这样做:
public function libraries(){
return $this->hasMany('App\Library', 'store_id','id');
}
Run Code Online (Sandbox Code Playgroud)
$store->libraries() or $library->store()
).试试这个。有用。将此添加到您的模型。
图书馆模式
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回答的最后一行。
归档时间: |
|
查看次数: |
21438 次 |
最近记录: |