2017-11-22 1 views
0

私は学生、教師、...が資格情報を使用してログインできる学校のプラットフォームを作成しています。重複データを減らすため、studentsという別のテーブルを作成せず、すべてのデータをusersテーブルに保存しました。サブタイプの雄弁なモデルを作成

ユーザーが学生かどうかを知るには、登録と呼ばれる表があります。この表には、user_id,schoolyear_idおよびclass_idが格納されています。

私はすでにユーザーテーブルを参照している学生モデルを作成しましたが、このモデルが学生にのみ通るようにするにはどうすればよいですか?

EER: EER overview

Student.php:

<?php 

namespace App; 

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

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

User.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();関数を呼び出すとき、私はすべてを得るということです学校に登録しているユーザー、つまり学生。

答えて

1

あなたの提供するソリューションは正しい方向に私を導きます。私の問題はグローバルスコープを使って解決します:

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

} 
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を返すと、通話が中断されるのが一般的です。そのロジックを検索されたイベントに適用すると、モデルインスタンスが学生でない場合は返されず、学生は返されます。ちょっとした考え。