Laravel 有许多 WhereNotIn 查询

Laravel HasMany WhereNotIn Query

Problem: I'm trying to query a PeopleType to find all the courses where a person isn't associated.

我有4张桌子

  1. 人物类型
  2. 课程
  3. People_Courses
  4. PeopleType_Courses

我有以下关系

人物模型

public function getPeopleType() {
  return $this->belongsTo('App\PeopleType','type_id');
}

public function getCourses() {
  return $this->belpngsToMany('App\Course','People_Courses','person_id','course_id');
}

PEOPLE_TYPE 型号

public function getPeople() {
  return $this->hasMany('App\Person','type_id');
}

public function getCourses() {
  return $this->belpngsToMany('App\Course','PeopleType_Courses','people_type_id','course_id');
}

我的尝试:

$peopleType = \App\PeopleType::FindOrFail(1);
$courses = $peopleType->getCourses()->whereNotIn('id', function($q) use($person) {
                $q->select('course_id')
                  ->from('People_Courses')
                    ->where('person_id', $person->id);
           })->get();

我的回复:

Integrity constraint violation: 1052 Column 'id' in IN/ALL/ANY subquery is ambiguous

人物课程Table示意图

Schema::create('People_Courses', function (Blueprint $table) {
   $table->increments('id');
   $table->integer('course_id');
   $table->integer('person_id');
);

PeopleType_Courses Table示意图

Schema::create('PeopleType_Courses', function (Blueprint $table) {
   $table->increments('id');
   $table->integer('course_id');
   $table->integer('people_type_id');
);

当您处理在查询中选择了相似列名的关系时,您需要通过为该列指定 table 名称来解决歧义。例如:

$peopleType->getCourses()->whereNotIn('courses.id', function($q)...  //courses.id