【发布时间】:2017-04-03 20:26:37
【问题描述】:
我有一个案例,其中 2 个 eloquent 模型应该从一个 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');
}
}
我想知道这样做是否正确?
【问题讨论】:
-
恕我直言,我只看到 Auth 存在问题。当前用户通过 id 从数据库中检索,因此您只能在一张表上进行身份验证:学生或导师。
-
@dparoli 我的意图是让 Auth 在用户表上工作,然后返回学生或导师对象。但我知道会发生什么样的问题。还有其他想法如何实现我想要做的吗?
-
@dparoli 我检查了 Entrust 包,但我对这种方法的问题是我需要为导师存储数据,而这些数据不应该为学生存储。 (我可能会忘记标准化:D)
标签: laravel inheritance laravel-5 eloquent