雄辩的模型继承层次结构

时间:2017-04-03 20:26:37

标签: laravel inheritance laravel-5 eloquent

我有一个案例,其中2个雄辩模型应该从User模型继承属性,但是User本身不应该作为独立实例存在。 (导师和学生,都继承自User类)。所以我现在正在做的是:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

abstract class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * Get the courses that the user has enrolled into
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */

    public function courses()
    {
        return $this->hasMany('App\Models\Course', 'user_course', 'user_id', 'course_id');
    }
}

class Student extends User
{
    protected $table = 'students';

    /**
     * Get the mentors that the user has hired
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */

    public function mentors()
    {
        return $this->hasMany('App\Models\User');
    }
}

class Mentor extends User
{
    protected $table = 'mentors';

    /**
     * Get a list of courses that a mentor is teaching
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */

    public function ownCourses()
    {
        return $this->hasMany('App\Models\Course', 'mentor_course', 'mentor_id', 'course_id');
    }
}

我想知道这是否是正确的做我想要完成的事情?

1 个答案:

答案 0 :(得分:1)

恕我直言,我将使用polymorhic relation

使用三个表:usersstudentsmentors;在users表格中添加两个字段:userable_id整数),userable_type字符串)。

用户模型

class class User extends Authenticatable
{
    public function userable()
    {
        return $this->morphTo();
    }

学生模特

class Student extends Model
{
    public function user()
    {
        return $this->morphOne('App\User', 'userable');
    }

导师模型

class Mentor extends Model
{
    public function user()
    {
        return $this->morphOne('App\User', 'userable');
    }

现在User::find($id)->userable会返回一个Student或Mentor对象,具体取决于userable_type的值

我将其他关系留给你,我希望这有帮助。