Laravel-一个表与其他两个表之间的关系
我有3个表:Laravel-一个表与其他两个表之间的关系,laravel,migration,pivot,Laravel,Migration,Pivot,我有3个表:用户,池,权限。用户和池具有透视表,因为它们具有多对多关系 权限条目仅由我手动创建。然后,每个池可以根据自己的用户认为合适的情况将权限分配给他们自己的用户。因此,用于将用户链接到权限的透视表需要同时具有pool\u id和user\u id和permission\u id 那么这个数据透视表是如何工作的呢?如何制作三向透视表 编辑:我的问题基本上是,没有满意的答案 对于链接3个模型的数据透视表,您需要在附加模型时发送附加数据,如以下回答所示: 您可以创建自定义关系类,例如ThreeB
用户
,池
,权限
。用户和池具有透视表,因为它们具有多对多关系
权限条目仅由我手动创建。然后,每个池可以根据自己的用户认为合适的情况将权限分配给他们自己的用户。因此,用于将用户链接到权限的透视表需要同时具有pool\u id
和user\u id
和permission\u id
那么这个数据透视表是如何工作的呢?如何制作三向透视表
编辑:我的问题基本上是,没有满意的答案 对于链接3个模型的数据透视表,您需要在附加模型时发送附加数据,如以下回答所示: 您可以创建自定义关系类,例如
ThreeBelongToMany
,该类将扩展BelongToMany
并重写attach()
方法
然后在涉及此类关系的模型上重写belongtomany()
方法(或使用其中的特征),以在适用时返回提到的自定义关系类,而不是泛型belongtomany
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);
}
此外,您还可以使用一些帮助程序获取这些相关模型,例如(为了灵活性,应使用方法获取键名,它们是硬编码的,以使其简短):
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);
}