【问题标题】:laravel 2 tables have 1:n relationship with the same tablelaravel 2表与同一张表有1:n关系
【发布时间】:2020-09-16 03:16:32
【问题描述】:

我有一个用户表、一个产品表和一个资产表。用户可以拥有许多资产,产品也可以,这意味着用户和产品都与资产具有 1:n 的关系。在 Laravel 中,如何在 Eloquent 中显示这种关系,这是一种多态关系,资产表列的结构类似于,

ID, type, file_path, ownable_id, ownable_type 

【问题讨论】:

  • 你是对的。只需将ownabe_id、ownable_type改为assetable_id和assetable_type

标签: php laravel eloquent


【解决方案1】:

我认为你的资产表列应该是

id、类型、file_path、assetable_id、assetable_type

将此关系添加到您的用户和产品模型

    public function assets()
    {
        return $this->morphMany(Asset::class, 'assetable');
    }

接下来,将此关系添加到您的资产模型中

public function assetable()
{
    return $this->morphTo();
}

【讨论】:

    【解决方案2】:

    用户模型的关系

     public function assets()
        {
            return $this->morphMany(Asset::class, 'assetable');
        }
    

    资产模型的关系

    public function assetable()
    {
        return $this->morphTo();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-15
      • 1970-01-01
      • 1970-01-01
      • 2020-02-21
      • 1970-01-01
      • 2018-04-28
      • 2019-12-25
      • 2016-01-26
      相关资源
      最近更新 更多