Laravel:一个表的多个模型

时间:2017-05-20 21:37:00

标签: laravel model eloquent relationships

我的目标:在桌面上维护所有用户(代理,管理员,学生,教师或更多角色),但每个模型/角色能够根据他们拥有的角色{{1来引用同一桌面上的另一个ID }}

注意:我已经有表格$admins = Agent::with('agent')->get();roles,但工作正常

user_roles

应用程序/ Agent.php:

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

应用程序/ Student.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');
    }
}

应用程序/ AgentStudent.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');
    }
}

1 个答案:

答案 0 :(得分:0)

为什么不把它作为自我参考?

class Agent extends Eloquent {

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

public function children()
{
    return $this->hasMany('App\Agent', 'parent_id');
}
}