【问题标题】:Laravel - Relationship between a table with two other tablesLaravel - 一个表与其他两个表之间的关系
【发布时间】:2014-05-15 06:49:16
【问题描述】:

我有 3 张桌子:userspoolspermissions。用户和池具有数据透视表,因为它们具有多对多关系。

权限条目仅由我手动创建。然后,每个池都可以按照他们认为合适的方式将权限分配给他们自己的用户。因此,用于将用户链接到权限的数据透视表需要同时具有pool_iduser_idpermission_id

那么这个数据透视表是如何工作的呢?如何制作三向数据透视表?

编辑:我的问题基本上是asked here,没有满意的答案!

【问题讨论】:

    标签: laravel migration pivot


    【解决方案1】:

    对于链接 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);
    }
    

    【讨论】:

      猜你喜欢
      • 2016-06-27
      • 2017-07-31
      • 1970-01-01
      • 2019-12-17
      • 1970-01-01
      • 2022-01-09
      • 2020-10-13
      • 2021-03-26
      • 1970-01-01
      相关资源
      最近更新 更多