简体   繁体   English

Laravel 多态有一个,两个不同的类别 model 到同一个项目

[英]Laravel Polymorphic HasOne ,two different categories model to the same item

I'm trying to use two different Category model to the same items table.我正在尝试将两个不同的类别 model 用于相同的items表。

I'v got 3 models我有3个模型

SystemCategory系统类别

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

UserCategory用户类别

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

Item物品

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

Item category could be either from system_categories or user_categories table项目类别可以来自system_categoriesuser_categories

I saw some Polymorphic relations but its about how two different models can belongs to one category, not about how model can belongs to two different category models我看到了一些多态关系,但它是关于两个不同的模型如何属于一个类别,而不是关于 model 如何属于两个不同的类别模型

Thanks.谢谢。

It can be done, first thing your schema looks ok but you want to set catagoryable_id to a bigInteger to match the id columns of the 2 category tables.可以这样做,首先您的架构看起来不错,但您想将 catagoryable_id 设置为 bigInteger 以匹配 2 个类别表的 id 列。

Then you would set your models up然后你会设置你的模型

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');
    }
}

Obviously this is presuming your models are in the App namespace显然这是假设您的模型在 App 命名空间中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM