繁体   English   中英

Laravel 5.3每个用户角色的不同字段键入如何使用多态实现它?

[英]Laravel 5.3 Different Fields Per User Role Type how to implement this using polymorphism?

标题说明了一切

例如

我希望主要的laravel用户模型具有不同类型的角色和每个角色

有不同的领域

用户具有Employee的角色

该角色将为用户提供不同的字段

你不需要在这里使用多态。 Laravel使用的User模型,你应该在这个模型中保留所有类似的数据。 然后创建Employee和其他模型。 然后,您应该在User和所有其他模型之间添加一对一关系。

class User extends Model
{ 
    public function employee()
    {
        return $this->hasOne('App\Employee');
    }
}

你可以这样做,使用多态关系

表结构将是:

managers
  id - integer
  title - string
  body - text

employees
    id - integer
    title - string
    url - string

users
    id - integer
    body - text
    userable_id - integer
    userable_type - string

roles
    id - integer
    name - string
    description - text

role_user
    id - integer
    role_id - integer
    user_id - integer

并且模型将被设计为:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get all of the owning userable models.
     */
    public function userable()
    {
        return $this->morphTo();
    }

    /**
     * User and Roles relationship
     */
    public function roles()
    {
        return $this->belongsToMany('App\Roles');
    }
}

class Employee extends Model
{
    /**
     * Get all of the employee's comments.
     */
    public function comments()
    {
        return $this->morphMany('App\Employee', 'userable');
    }
}

class Manager extends Model
{
    /**
     * Get all of the manager's comments.
     */
    public function comments()
    {
        return $this->morphMany('App\Manager', 'userable');
    }
}

class Role extends Model
{
    /**
     * Relationship with User and Role Models
     */
    public function users()
    {
        return $this->belongsToMany('App\User');
    }
}

希望这可以帮助!

暂无
暂无

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

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