ฉันมีสคีมาสองสามแบบเช่นนั้น
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('userName')->default('');
$table->string('userEmail')->default('');
$table->tinyInteger('active')->default(1);
$table->integer('departmentId')->unsigned()->default(0);
$table->foreign('departmentId')->references('departmentId')->on('departments')->onDelete('cascade');
$table->timestamps();
});
Schema::create('departments', function (Blueprint $table) {
$table->primary('departmentId');
$table->integer('departmentId')->unsigned()->default(0);
$table->string('departmentName')->default('');
$table->tinyInteger('active')->default(1);
$table->timestamps();
});
ดังนั้นผู้ใช้จึงอยู่ในแผนก และแผนกสามารถมีผู้ใช้ได้หลายคน
ในคอนโทรลเลอร์ตัวหนึ่งของฉัน ฉันใช้ทำสิ่งต่อไปนี้เพื่อรับรายชื่อผู้ใช้สำหรับแผนกเฉพาะ
$users = User::select('userName', 'id')->where('departmentId', 2)->get();
เนื่องจากฉันได้รับแผนกต่างๆ จาก Active Directory ฉันจึงค้นพบว่านี่ไม่ใช่วิธีที่ดีเนื่องจากรหัสสำหรับแผนกต่างๆ เปลี่ยนไป ด้วยเหตุนี้ ตอนนี้ฉันจึงต้องรับผู้ใช้ผ่านทาง departmentName แทน ในขณะนี้ฉันกำลังลองสิ่งนี้
$test = DB::table('users')
->join('departments', 'users.departmentId', '=', 'departmentId')
->select('users.userName', 'users.id')
->get();
อย่างไรก็ตาม สิ่งนี้จะส่งกลับข้อผิดพลาดต่อไปนี้
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'departmentId' in on clause is ambiguous (SQL: select `users`.`userName`, `users`.`id` from `users` inner join `departments` on `users`.`departmentId` = `departmentId`)
เป็นไปได้อย่างไรที่จะรับผู้ใช้ทั้งหมดสำหรับชื่อแผนกใดแผนกหนึ่ง? สมมติว่าฉันต้องการรับผู้ใช้ทั้งหมดที่อยู่ในแผนกเทคโนโลยี ฉันจะทำเช่นนี้ได้อย่างไร?
ขอบคุณ