laravel - 具有自定义名称的 hasMany、belongsTo、belongsToMany 参数?
问题描述
我有这些数据库表:
author (atr_id pk) // model : Author
category (ctg_id pk) // model : Category
post (pst_id pk, pst_atr_id fk) // model : Post
post_categories (pct_pst_id fk, pct_ctg_id fk) // pivot : PostCategories
如何使用自定义名称定义 hasMany、belongsTo、belongsToMany 参数?
型号:作者
public function getPosts()
{
return $this->hasMany('App\Post', ?, ?);
}
型号 : 邮政
public function getAuthor()
{
return $this->belongsTo('App\Author', ?, ?);
}
public function getCategories()
{
return $this->belongsToMany('App\Category', ?, ?, ?);
}
型号 : 类别
public function getPosts()
{
return $this->belongsToMany('App\Post', ?, ?, ?);
}
解决方案
型号:作者
<?php
public function getPosts(){
return $this->hasMany('App\Post','pst_atr_id');// author table's foreign key in Post table.
}
型号 : 邮政
<?php
public function getAuthor(){
return $this->belongsTo('App\Author','pst_atr_id','atr_id'); // first is foreign key of author table in this current table and second is primary key name of author table.
}
public function getCategories(){
return $this->belongsToMany('App\Category','post_categories','pct_pst_id ','pct_ctg_id'); /* 'post_categories' is the pivot table. Rest 2 parameters- first is foreign key present in post_categories of the current model, second is foreign key present in post_categories of the model we are relating with*/
}
型号 : 类别
<?php
public function getPosts(){
return $this->belongsToMany('App\Post','post_categories ','pct_ctg_id','pct_pst_id');
/* 'post_categories' is the pivot table. Rest 2 parameters- first is foreign key present in post_categories of the current model, second is foreign key present in post_categories
of the model we are relating with*/
}
推荐阅读
- android - 有没有办法通过点击 Compose Scaffold 中的 TopAppBar 中的 IconButton 打开网页?
- python - Pandas 通过数据框搜索缺少变音符号的单词
- python - 使用 selenium_python 抓取类下的属性
- python - python小提琴图规则轴
- xamarin - Shell BackButtonBehavior 命令绑定在 UWP 中不起作用
- reactjs - Jest with Styled Components 错误:解析预期 css 的语法错误:缺少 '}'
- python-3.x - 将日期与 Pandas 中的多列进行比较
- amazon-web-services - 如何将 AWS EC2 从 t2.2xlarge 升级到 t3.2xlarge?
- html - 如何修复在整行上工作的悬停选项
- python - 从 1 到 n 顺序编号的周末日期