BelongsToMany与BelongsToMany的关系

时间:2016-11-29 15:11:04

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

我需要从belongsToMany与belongsToMany的关系中获取数据,它会如此:我的模型中的A-> B-> C将是provider-> 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);
   }
}

数据库看起来像:

提供商

ID

名称

EVENT_TYPE

ID

名称

字幕

ID

名称

caption_event_type

caption_id

event_type_id

caption_provider

caption_id

PROVIDER_ID

Thnks。

1 个答案:

答案 0 :(得分:0)

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

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();

希望这有帮助!

相关问题