Laravel 有很多 WhereNotIn 查询

开发者

问题:我正在尝试查询 PeopleType 以查找与某个人无关的所有课程。

我有4张桌子

  1. 人们
  2. 人物类型
  3. 课程
  4. People_课程
  5. PeopleType_课程

我有以下关系

人物模型

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();

我的回复:

违反完整性约束:IN/ALL/ANY 子查询中的 1052 列“id”不明确

人员课程表示意图

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

PeopleType_Courses 表示意图

Schema::create('PeopleType_Courses', function (Blueprint $table) {
   $table->increments('id');
   $table->integer('course_id');
   $table->integer('people_type_id');
);
奥卢瓦托比塞缪尔·奥米萨金

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章