【问题标题】:Make eloquent model for subtype为子类型制作雄辩的模型
【发布时间】:2017-11-22 12:52:46
【问题描述】:

我正在创建一个学校平台,学生、教师……可以使用他们的凭据登录。为了减少重复数据,我没有单独创建一个名为 students 的表,而是将所有数据保存在 users 表中。

要知道用户是否是学生,我有一个名为 enrolments 的表,在此表中存储了 user_idschoolyear_idclass_id

我已经做了一个引用 users 表的学生模型,但是如何确保这个模型只通过学生?

能效比:

学生.php:

<?php

namespace App;

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

    public function enrollments(){
        return $this->belongsToMany(Enrollment::class);
    }
}

用户.php:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Support\Facades\Auth;

class User extends Authenticatable
{
    use Notifiable;
    use HasRoles;

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

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

    public function profiles(){
        return $this->hasOne(Profile::class);
    }

}

我想要实现的是,当我调用Student::all(); 函数时,我得到所有在学校注册的用户,因此是学生。

【问题讨论】:

    标签: php laravel eloquent laravel-5.5


    【解决方案1】:

    查看模型事件:https://laravel.com/docs/5.5/eloquent#events

    你应该可以把它放到你的学生模型中进行测试:

    protected static function boot(){
            parent::boot();
            static::retrieved(function($thisModel){
                if($thisModel->isNotAStudent or whatever logic you need){
                      return false;
                }
            }
        }
    

    我仍在使用 5.4,它没有内置检索到的模型事件,但返回 false 通常会阻止调用通过。因此,将该逻辑应用于检索到的事件可能会阻止返回该模型实例(如果它不是学生),但允许返回学生。只是一个想法。

    【讨论】:

      【解决方案2】:

      您提供的解决方案将我引向正确的方向。我的问题通过使用全局范围解决了:

      <?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);
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2021-08-11
        • 2021-05-07
        • 1970-01-01
        • 2013-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-15
        相关资源
        最近更新 更多