php - Laravel 模型关系 - 我想建立什么样的关系?
问题描述
我有 3 个与这个问题相关的模型;国家、制造商和地区。
为了这个问题,我已经简化了表格。我认为表格中的任何其他内容或任何其他模型都与该问题无关。
我的桌子是这样设置的;
manufacturers
- id
- name
countries
- id
- name
regions
- id
- name
- manufacturer_id
- country_id
我想要做的是$manufacturer->countries
在我的刀片中写入并让它吐出与给定制造商相关的国家。
这些模型目前是这样相互关联的;
国家.php
public function manufacturers()
{
return $this->hasMany(Manufacturer::class);
}
public function regions()
{
return $this->hasMany(Region::class);
}
区域.php
public function manufacturer()
{
return $this->belongsTo(Manufacturer::class);
}
public function country()
{
return $this->belongsTo(Country::class);
}
以及我遇到问题的地方,Manufacturer.php
我想我需要一个 hasMany 关系。我已经有了;
public function regions()
{
return $this->hasMany(Region::class);
}
我会认为我会需要;
public function countries()
{
return $this->hasManyThrough(Country::class,Region::class);
}
但这会导致这个错误;
Column not found: 1054 Unknown column 'countries.region_id' in 'on clause' (SQL: select `countries`.*, `regions`.`manufacturer_id` as `laravel_through_key` from `countries` inner join `regions` on `regions`.`id` = `countries`.`region_id` where `regions`.`manufacturer_id` = 4)
所以我尝试交换课程来给予;
public function countries()
{
return $this->hasManyThrough(Region::class,Country::class);
}
但这会导致;
Column not found: 1054 Unknown column 'countries.manufacturer_id' in 'field list' (SQL: select `regions`.*, `countries`.`manufacturer_id` as `laravel_through_key` from `regions` inner join `countries` on `countries`.`id` = `regions`.`country_id` where `countries`.`manufacturer_id` = 4)
有谁知道我应该如何建立我的关系以实现我想要的?
我还尝试了一种belongsToMany
关系,它确实带回了国家,但同一个国家的多个实例。我只想要出现在任何给定制造商的区域表中的每个国家的一个实例。
解决方案
在Laravel
中,最好应用的关系是many to many
关系。这适用于您的情况意味着 1country
可以有多个manufacturers
,1manufacturer
可以在多个国家/地区。
如果是这种情况,你不需要创建一个regions
表,而是一个pivot table.
laravel 中的默认命名约定是(单数和 om 字母顺序),即country_manufacturer
table 并且它将包含(你总是可以添加一个额外的变量称为pivot
值):
country_manufacturer
- id
- name // pivot value
- manufacturer_id
- country_id
然后,在模型中,添加belongsToMany
关系,即
在制造商模型中(无枢轴):
public function countries()
{
return $this->belongsToMany(Manufacturer::class);
}
在国家模式中(有支点):
public function manufacturers()
{
return $this->belongsToMany(Country::class)->withPivot('name');
}
因此,您将能够调用 $country->manufacturers()
它将为您提供所有制造商的列表,$country
反之亦然:$manufacturer->countries
将为您提供制造商所在的所有国家/地区。
推荐阅读
- javascript - 如何检查用户是否在 AWS Amplify 中被确认?
- javascript - Bot 框架范围 beginDialogAction
- html - 覆盖 * scss 页面中的 CSS 属性
- reactjs - 实施redux-persist后反应本机应用程序保持空白?
- java - 现有 Camel REST 端点的 OAuth2
- c# - 在 XXX 上没有可以接受消息的端点监听。这通常是由不正确的地址或 SOAP 操作引起的
- java - 无法更新摆动中的文本区域
- python-3.x - Python3.6 - TypeError:'int'对象不可下标
- java - rxjava:平面图和地图之间的区别
- ruby-on-rails - 表格/网格中的表格