Php 为子类型建立雄辩的模型
我正在创建一个学校平台,学生、老师,。。。可以使用他们的凭据登录。为了减少重复数据,我没有单独创建一个名为students的表,而是将所有数据保留在users表中 为了知道用户是否是学生,我有一个名为enrolments的表,在这个表中存储了Php 为子类型建立雄辩的模型,php,laravel,eloquent,laravel-5.5,Php,Laravel,Eloquent,Laravel 5.5,我正在创建一个学校平台,学生、老师,。。。可以使用他们的凭据登录。为了减少重复数据,我没有单独创建一个名为students的表,而是将所有数据保留在users表中 为了知道用户是否是学生,我有一个名为enrolments的表,在这个表中存储了用户id,学年id和班级id 我已经创建了一个引用用户表的学生模型,但是如何确保该模型只通过学生 EER: Student.php: <?php namespace App; class Student extends User { pr
用户id
,学年id
和班级id
我已经创建了一个引用用户表的学生模型,但是如何确保该模型只通过学生
EER:
Student.php:
<?php
namespace App;
class Student extends User
{
protected $table= 'users';
public function enrollments(){
return $this->belongsToMany(Enrollment::class);
}
}
签出模型事件:
您应该能够将其放入学生模型中进行测试:
protected static function boot(){
parent::boot();
static::retrieved(function($thisModel){
if($thisModel->isNotAStudent or whatever logic you need){
return false;
}
}
}
我仍然使用5.4,它没有内置检索到的模型事件,但是返回false通常会阻止调用。因此,如果模型实例不是学生,将该逻辑应用于检索到的事件可能会阻止该模型实例返回,但允许学生返回。只是一个想法 查看模型事件:
您应该能够将其放入学生模型中进行测试:
protected static function boot(){
parent::boot();
static::retrieved(function($thisModel){
if($thisModel->isNotAStudent or whatever logic you need){
return false;
}
}
}
我仍然使用5.4,它没有内置检索到的模型事件,但是返回false通常会阻止调用。因此,如果模型实例不是学生,将该逻辑应用于检索到的事件可能会阻止该模型实例返回,但允许学生返回。只是一个想法 您提供的解决方案为我指明了正确的方向。我的问题通过使用全局范围解决:
<?php
namespace App;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
class Student extends User
{
protected $table= 'users';
protected static function boot()
{
parent::boot();
static::addGlobalScope('student', function (Builder $builder) {
$builder->whereExists(function ($query) {
$query->select(DB::raw(1))
->from('enrollments')
->whereRaw('enrollments.user_id = users.id');
});
});
}
public function enrollments(){
return $this->belongsToMany(Enrollment::class);
}
}
您提供的解决方案为我指明了正确的方向。我的问题通过使用全局范围解决:
<?php
namespace App;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
class Student extends User
{
protected $table= 'users';
protected static function boot()
{
parent::boot();
static::addGlobalScope('student', function (Builder $builder) {
$builder->whereExists(function ($query) {
$query->select(DB::raw(1))
->from('enrollments')
->whereRaw('enrollments.user_id = users.id');
});
});
}
public function enrollments(){
return $this->belongsToMany(Enrollment::class);
}
}