对于链接 3 个模型的数据透视表,您需要在附加模型时发送额外的数据,如此答案:Laravel - Pivot table for three models - how to insert related models?:
$model->relation()->attach($otherModel, ['thirdModelKeyName' => 'thirdModelKeyValue']);
您可以创建自定义关系类,例如ThreeBelongsToMany,它将扩展belongsToMany 并覆盖attach() 方法。
然后在您的模型上覆盖belongsToMany() 方法,该方法涉及此类关系(或在那里使用特征)以返回提到的自定义关系类而不是通用的belongsToMany(如果适用)。
attach() 方法可能如下所示:
public function attach($id, array $attributes = array(), $touch = true, $otherId = null)
{
if ( ! is_null($otherId))
{
if ($otherId instanceof Model) $otherId = $otherId->getKey();
$attributes[$this->getThirdKey()] = $otherId;
}
return parent::attach($id, $attributes, $touch);
}
您还可以使用一些帮助器来获取这些相关模型,例如(应使用方法获取键名以提高灵活性,它们经过硬编码以使其简短):
/**
* Accessor for far related model (thru pivot)
*
* @return mixed
*/
public function getTrackAttribute()
{
if (is_null($this->pivot)) return null;
if (is_null($this->pivot->track_id)) return null;
return ($this->pivot->track) ?: $this->pivot->track = Track::find($this->pivot->track_id);
}