[英]Laravel HasMany WhereNotIn Query
問題:我正在嘗試查詢 PeopleType 以查找與某個人無關的所有課程。
我有4張桌子
我有以下關系
人物模型
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.