Laravel变形属于?

时间:2017-07-07 16:01:28

标签: laravel polymorphism

我遇到多个表与belongsTo中的类别表有laravel 5.4关系的情况。

所以我想到了这个结构:

用户表:

id
name
email
category_id   <--

类别表

id
model_type
name

这可能与morph关系有效吗?

1 个答案:

答案 0 :(得分:1)

这不是因为model_type只是哪些类别可用于哪些模型的约束。如果你这样设置,你会在每个模型的关系上添加约束,如:

class User extends Model
{
    // User class

    public function category()
    {
        return $this->belongsTo(Category::class)->where('model_type', '=', static::class);
    }
}

或者,由于您有许多属于Category的模型,您可以更进一步,使用特征表示关系,并将特征放在属于Category的每个模型上:

trait BelongsToCategory()
{
    public function category()
    {
        return $this->belongsTo(Category::class)->where('model_type', '=', static::class);
    }
}

class User extends Model
{
    use BelongsToCategory;

    // User class
}