【问题标题】:Laravel HasMany WhereNotIn QueryLaravel 有很多 WhereNotIn 查询
【发布时间】:2020-05-02 08:26:48
【问题描述】:

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

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

我的回复:

违反完整性约束: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');
);

【问题讨论】:

    标签: php laravel laravel-5 eloquent eloquent-relationship


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-10-26
      • 2019-03-14
      • 2018-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-17
      • 2023-02-13
      相关资源
      最近更新 更多