0

我正在尝试对同items一张表使用两个不同的类别模型。

我有3个模型

系统类别

Schema::create('system_categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->timestamps();
    });

用户类别

Schema::create('user_categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->integer('user_id');
        $table->timestamps();
    });

物品

Schema::create('items', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->integer('categoryable_id');
        $table->string('categoryable_type');
        $table->timestamps();
    });

项目类别可以是来自system_categoriesuser_categories

我看到了一些多态关系,但它是关于两个不同的模型如何属于一个类别,而不是关于模型如何属于两个不同的类别模型

谢谢。

4

1 回答 1

2

可以这样做,首先您的架构看起来不错,但您想将 catagoryable_id 设置为 bigInteger 以匹配 2 个类别表的 id 列。

然后你会设置你的模型

class Item extends Model
{
    public function categoryable() 
    {
        return $this->morphTo();
    }
}

class SystemCategory extends Model
{
    public function items()
    {
        return $this->morphMany('App\Item', 'categoryable');
    }
}

class UserCategory extends Model
{
    public function items()
    {
        return $this->morphMany('App\Item', 'categoryable');
    }
}

显然这是假设您的模型在 App 命名空间中

于 2020-06-07T12:29:15.193 回答