Saturday, May 20, 2017

Laravel: Multiple model for one table

My Goals
1. maintain all users (agents, admins, students, teachers or can be more role) in on table but each individual model/role able to reference to another id on the same table base on role they have $admins = Agent::with('agent')->get();

NOTE: I already have table 'roles' and 'user_roles' which working just fine

users
===========
id
username
password
fullname

 

agent_student (one agent has many students but one student belongsTo one agent)
===========
id
agent_id
student_id

 

admin_agent (one admin has many agents but one agent belongsTo one admin)
===========
id
admin_id
agent_id

 

App\Agent.php
============
namespace App;

use Illuminate\Database\Eloquent\Model;

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

public function student() {
return $this->hasMany('App\Student', 'id');
}

function agent_student() {
return $this->hasMany('App\AgentStudent', 'id');
}
}

 

App\Student.php
============
namespace App;

use Illuminate\Database\Eloquent\Model;

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


public function agent() {
return $this->belongsTo('App\Agent', 'id');
}

public function agent_student() {
return $this->hasOne('App\AgentStudent', 'student_id');
}

}

 

App\AgentStudent.php
====================
namespace App;

use Illuminate\Database\Eloquent\Model;

class UserStudent extends Model
{
protected $table = 'user_student';

function student() {
return $this->hasOne('App\Student', 'id');
}

function agent() {
return $this->belongsTo('App\Agent', 'id');
}
}



via Kobe Jogkaew

Advertisement