我不认为这种关系可以直接建立,但我有其他选择。
您需要一个名为“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');
}
这就是多对多多态关系的工作原理。
----------------------- 对评论的回应 -------------------- ---
当您希望将 People 与 Cars 联系起来时:
$people->cars()->sync( array(
1 => array( 'source_type' => 'People', 'target_type' => 'Cars' ),
2 => array( 'source_type' => 'People', 'target_type' => 'Cars' ),
...
));