dongtiao0657 2019-07-04 08:41
浏览 87

Laravel模型关系 - 我想创建什么样的关系?

I have got 3 models associated with this question; Country, Manufacturer and Region.

I've simplified the tables for the sake of this question. I don't think anything else in the tables or any of the other models are anything to do with the problem.

My tables are set up like so;

manufacturers
 - id
 - name

countries
 - id
 - name

regions
 - id
 - name
 - manufacturer_id
 - country_id

What I want to be able to do is to write $manufacturer->countries in my blade and have it spit out the countries that are associated with a given manufacturer.

The models are currently related to each other like this;

Country.php

public function manufacturers()
{
    return $this->hasMany(Manufacturer::class);
}

public function regions()
{
    return $this->hasMany(Region::class);
}

Region.php

public function manufacturer()
{
    return $this->belongsTo(Manufacturer::class);
}

public function country()
{
    return $this->belongsTo(Country::class);
}

and where I'm having the problem, Manufacturer.php

I think I need a hasMany relationship. I've already got;

public function regions()
{
    return $this->hasMany(Region::class);
}

and I would have thought I would have needed;

public function countries()
{
    return $this->hasManyThrough(Country::class,Region::class);
}

but that leads to this error;

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)

so I tried swapping the classes round to give;

public function countries()
{
    return $this->hasManyThrough(Region::class,Country::class);
}

but that leads to;

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)

Does anyone know how I should be setting my relationships up in order to achieve what I want?

I also tried a belongsToMany relationship, which did bring back the countries, but multiple instances of the same country. I just want one instance of each country that appears in the regions table for any given manufacturer.

  • 写回答

2条回答 默认 最新

  • dongluojiao6322 2019-07-04 08:49
    关注

    You are actually dealing with the many-to-many relationship.

    In your case regions is a pivot table.

    Kindly check belongsToMany.

    评论

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失