【问题标题】:BelongsToMany with BelongsToMany relation [closed]BelongsToMany 与 BelongsToMany 关系[关闭]
【发布时间】:2016-11-29 15:11:03
【问题描述】:

我需要从与 belongsToMany 的关系 belongsToMany 中获取数据,结果会是这样:我的模型中的 A->B->C 将是 providers->caption->eventType,所以你需要从一个事件类型。

模型看起来像:

提供者模型

Class Provider extends Model {
   public function captions() {
      return $this->belongsToMany(Caption::class);
   }
}

字幕模型

Class Caption extend Model {
   public function event_type() {
      return $this->belongsToMany(Event_type::class);
   }
   public function providers() {
      return $this->belongsToMany(Provider::class);
   }
}

事件类型模型

Class Event_type extends Model {
   public function captions() {
      return $this->belongsToMany(Caption::class);
   }
}

数据库如下:

供应商

身份证

名字

event_type

身份证

名字

字幕

身份证

名字

caption_event_type

caption_id

event_type_id

caption_provider

caption_id

provider_id

谢谢。

【问题讨论】:

  • 请添加您的关系和/或模型,否则无法帮助您。
  • 型号与合作伙伴 Saumya Rastogi 评论的型号相同,谢谢

标签: php laravel eloquent has-and-belongs-to-many


【解决方案1】:

根据我的理解,我们的模型结构应该是这样的:

class Provider extends Model {
    public function captions()
    {
        return $this->belongsToMany(Caption::class);
    }
}

class EventType extends Model {
    public function captions()
    {
        return $this->belongsToMany(Caption::class);
    }
}

class Caption extends Model {
    public function providers()
    {
        return $this->belongsToMany(Provider::class);
    }

    public function eventTypes()
    {
        return $this->belongsToMany(EventType::class);
    }
}

要获得providers 的所有EventType,您可以这样:

$captions = EventType::find(1)->captions;

foreach($captions as $caption)
{
    $providers_arr[] = $caption->providers;
}

$providers_collection = collect($providers_arr)->unique();

希望这会有所帮助!

【讨论】:

  • 嗨,正如你所说,我在模型中的关系是这样的,但是当我想通过 $event->captions ()->providers 获取数据时,我收到此错误:未定义的属性: Illuminate \ Database \ Eloquent \ Collection :: $providers
  • 哦,那是我的错,请参阅上面的更新答案!
  • 谢谢兄弟,对我帮助很大
猜你喜欢
  • 2014-12-30
  • 2017-07-25
  • 2018-05-19
  • 2015-02-22
  • 2020-12-16
  • 2020-12-14
  • 2019-10-01
  • 2015-01-16
  • 2018-01-31
相关资源
最近更新 更多