【问题标题】:laravel eloquent pivot with primary id to reference to another pivotlaravel 雄辩的枢轴与主 id 来引用另一个枢轴
【发布时间】:2019-07-24 21:35:25
【问题描述】:

我对数据透视表之间的关系有疑问。

我在国家和街道之间有多对多关系,但是这个(数据透视表)的主键与数字有多对多关系。

我需要这个列表(有口才):

$country = Country::findOrFail(1)->with('streets', 'numbers')
foreach ($country->streets as $street){
    foreach($street->numbers as $number) {
       $number;
    }
}

或者存在任何解决方案?

这只是一个例子。表的正式名称已更改。

示例结构:

Table Countries
    id
    name

Table Streets
    id
    name

Table country_street
   id
   country_id
   street_id

Table number_country_street
   id
   number_id
   country_street_id

Table numbers
   id
   name

感谢您的帮助。

【问题讨论】:

  • 恕我直言,我认为您的支点应该建模,尝试添加模型 CountryStreet,关系应该变得更容易。
  • @dparoli 你能给我模型类 CountryStreet 与关系吗?

标签: php laravel eloquent pivot many-to-many


【解决方案1】:

@dparoli 有个好主意。

有时对于多对多关系使用继承 Pivot 类,但现在没关系。

所以现在我们可以使用下面的这些代码进行列表。

$country = Country::findOrFail(1);
foreach ($country->countryStreet as $countryStreet){
    echo $countryStreet->street->name
    foreach($countryStreet->numbers as $number) {
       $number;
    }
}

class Countries
     public function countryStreet()
     {
         return $this->hasMany(CountryStreet::class, 'country_id', 'id');
     }

Class CountryStreet with method block() using relation hasOne

另一个实现已经启动。

【讨论】:

    【解决方案2】:

    恕我直言,我将定义一个额外的模型:CountryStreet,类似这样的:

    // CountryStreet
    class CountryStreet extends Model
    {
        public function city()
        {
             return $this->belongsTo('App\City');
        }
    
        public function street()
        {
             return $this->belongsTo('App\Street');
        }
        public function numbers()
        {
             return $this->belongsToMany('App\Number', 'number_country_street');
        }
    }
    
    // Country
    class Country extends Model
    {
        public function streets()
        {
             return $this->hasManyThrough('App\Street', 'App\CountryStreet');
        }
    }
    
    // Streets
    class Street extends Model
    {
        public function countries()
        {
             return $this->hasManyThrough('App\Country', 'App\CountryStreet');
        }
    }
    
    // Number
    class Number extends Model
    {
        public function country_streets()
        {
             return $this->belongsToMany('App\CountryStreet', 'number_country_street');
        }
    }
    

    【讨论】:

    • class CountryStreet 扩展 Model 或 Pivot,因为它是数据透视表?
    猜你喜欢
    • 2020-10-26
    • 2018-05-19
    • 2017-05-24
    • 1970-01-01
    • 2018-01-10
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 2020-05-13
    相关资源
    最近更新 更多