雄辩:如何得到逆

时间:2016-04-26 06:51:52

标签: php laravel eloquent

我有三张桌子:

  1. 人物(包含列:id& name)
  2. 分配(包含列:person_id& project_id)
  3. 项目(包含列:id和标题)
  4. 我有分配表,因为每个人都可以分配到许多项目。

    我有这三种模式:

    // People.php 
    public function projectAssigned()
    {
        return $this->hasMany('App\Assignment', 'person_id');
    } 
    
    // Assignment.php
    public function person()
    {
         return $this->belongsTo('App\People', 'person_id');
    }  
    
    public function project()
    {
         return $this->belongsTo('App\Project', 'project_id');
    }
    
    public function task()
    {
         return $this->hasMany('App\Task', 'assignment_id');
    } 
    
    // Project.php
    public function assignment()
    {
        return $this->hasMany('App\Assignment', 'project_id');
    }
    

    获取特定项目中分配的人员列表很简单:

    how I get it:
    @foreach($project->assignment as $person)
    <tr>
    <td>{{$person->person->firstname.' '.$person->person->lastname}}</td>
    </tr>
    @endforeach
    

    我的问题是:如何获取特定项目中未分配的人员列表?

1 个答案:

答案 0 :(得分:0)

例如,在您的Person模型添加方法中:

public function getNotInProject($projectId) {
    return $this
        ->leftJoin('assignment', 'assignment.person_id', '=', 'person.id')
        ->where('assignment.project_id', '<>', $projectId)
        ->get();
}

然后你会得到一些人:

@foreach(Person::getNotInProject($project->id) as $person)
    <tr>
        <td>{{$person->firstname.' '.$person->lastname}}</td>
    </tr>
@endforeach