我有一个表存储,并且存储库有很多库,在库中我有商店的外键 store_id
.
存储表
id(PK)
图书馆表
id(PK)
store_id(FK)
我对 hasMany
和 belongsTo
参数包含了疑惑,在docs中它说
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,所以我总是想指定哪个是外键和主键
2 回答
要简化语法,请将
return $this->hasMany('App\Comment', 'foreign_key', 'local_key');
参数视为:要链接到的模型
外部表的列(您链接到的表)链接回当前表的
id
列(除非您指定第三个参数,在这种情况下它将使用它)应该使用的当前表的列 - 即,如果您不希望另一个表的外键链接到当前表的
id
列在您的情况下,因为您在
libraries
表中使用了store_id
,所以您自己的生活很轻松 . 在Store
模型中定义时,下面应该可以正常工作:在幕后,Laravel会自动将
Store
表的id
列链接到Library
表的store_id
列 .如果你想明确定义它,那么你会这样做:
$store->libraries() or $library->store()
) .试试这个吧 . 有用 . 将其添加到您的模型中 .
Library model
Store model
example code.