【问题标题】:Bidrectional many 2 many morph models in LaravelLaravel 中的双向多 2 多变形模型
【发布时间】:2015-11-23 03:20:49
【问题描述】:

我有 3-4 种不同的型号:

  • 汽车
  • 办公室

所以这三个之间有many2many关系:

People <-> Cars
Cars <-> Offices
People <-> Offices

有没有一种方法可以定义一个具有双变形的单个数据透视表,具有这样的 MySQL 表

- id
- target_id
- target_type
- source_id
- source_type

这样我可以将任何新模型添加到图片中。

【问题讨论】:

  • 我认为使用 Laravel/Eloquent 的普通东西是不可行的。不过,我想您可能可以扩展和扩充 MorphToMany 类来添加这种功能。

标签: laravel orm laravel-5 eloquent


【解决方案1】:

我不认为这种关系可以直接建立,但我有其他选择。

您需要一个名为“people_car_office”的数据透视表:

- id 
- target_id
- target_type
- source_id
- source_type

人物模型:

public function cars(){
     return $this->belongsToMany('Cars', 'people_car_office', 'target_id', 'source_id')->wherePivot('source_type', '=', 'People')->wherePivot('target_type','=','Cars');
    }

public function offices(){
     return $this->belongsToMany('Offices', 'people_car_office', 'target_id', 'source_id')->wherePivot('source_type', '=', 'People')->wherePivot('target_type','=','Offices');
    }

Cars 模型:

public function people(){
     return $this->belongsToMany('People', 'people_car_office', 'target_id', 'source_id')->wherePivot('source_type', '=', 'Cars')->wherePivot('target_type','=','People');
    }

public function offices(){
     return $this->belongsToMany('Offices', 'people_car_office', 'target_id', 'source_id')->wherePivot('source_type', '=', 'Cars')->wherePivot('target_type','=','Offices');
    }

办公室模型:

public function cars(){
     return $this->belongsToMany('Cars', 'people_car_office', 'target_id', 'source_id')->wherePivot('source_type', '=', 'Offices')->wherePivot('target_type','=','Cars');
    }

public function people(){
     return $this->belongsToMany('People', 'people_car_office', 'target_id', 'source_id')->wherePivot('source_type', '=', 'Offices')->wherePivot('target_type','=','People');
    }

这就是多对多多态关系的工作原理。

----------------------- 对评论的回应 -------------------- ---

当您希望将 PeopleCars 联系起来时:

$people->cars()->sync( array( 
     1 => array( 'source_type' => 'People', 'target_type' => 'Cars' ),
     2 => array( 'source_type' => 'People', 'target_type' => 'Cars' ),
     ...
));

【讨论】:

  • 听起来可信。实际上,您每次使用 3 个字段(取决于您需要什么)建立多态关系。当你连接一个人的实例和一个汽车的实例时会发生什么。它会在数据透视表中创建 thow roes 吗?
  • 当您从 People 检索 Cars 实例时,会检索到 Object Cars,其中包含人与汽车之间关系的所有结果
猜你喜欢
  • 2013-04-13
  • 1970-01-01
  • 1970-01-01
  • 2020-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多