首页 > 解决方案 > 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关系,它确实带回了国家,但同一个国家的多个实例。我只想要出现在任何给定制造商的区域表中的每个国家的一个实例。

标签: phplaravelrelationship

解决方案


Laravel中,最好应用的关系是many to many关系。这适用于您的情况意味着 1country可以有多个manufacturers,1manufacturer可以在多个国家/地区。

如果是这种情况,你不需要创建一个regions表,而是一个pivot table.laravel 中的默认命名约定是(单数和 om 字母顺序),即country_manufacturertable 并且它将包含(你总是可以添加一个额外的变量称为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将为您提供制造商所在的所有国家/地区。


推荐阅读