in my laravel app I'm gtting the following error, I think it's because the relation is incorrectly formed?
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select * from `badges` where exists (select * from `users` inner join `user_badge` on `users`.`id` = `user_badge`.`user_id` where `badges`.`id` = `user_badge`.`badge_id` and `id` = 1) and `badgecategory_id` = 4 limit 1)\
Method triggering the error.
public function syncBadges(Request $request)
{
$user = User::with('badges')->findOrFail($request['user_id']);
$badge = Badge::whereHas('users', function ($query) use ($request){
$query->where('id' , $request['user_id']);
})
->where('badgecategory_id',$request['badgecategory_id'])
->first();
if($badge)
{
$user->badges()->dettach($badge['id']);
$user->badges()->attach($request['badge_id']);
}
else
{
$user->badges()->attach($request['badge_id']);
}
}
User Model:
public function badges()
{
return $this->belongsToMany('App\Models\Badge', 'user_badge', 'user_id', 'badge_id');
}
Badge Model:
protected $table = 'badges';
public function users()
{
return $this->belongsToMany('App\Models\User', 'user_badge', 'badge_id', 'user_id');
}
public function category()
{
return $this->belongsTo('App\Models\BadgeCategory', 'badgecategory_id');
}
Bage table migration
public function up()
{
Schema::create('badges', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('badgecategory_id')->index();
$table->foreign('badgecategory_id')->references('id')->on('badgecategories')->onDelete('cascade')->onUpdate('cascade');
$table->string('title');
$table->string('icon')->nullable();
$table->timestamps();
});
}
User Badge Pivot table migration
class CreateUserBadgeTable extends Migration
{
public function up()
{
Schema::create('user_badge', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id')->index()->nullable();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
$table->unsignedInteger('badge_id')->nullable()->index();
$table->foreign('badge_id')->references('id')->on('badges')->onDelete('cascade')->onUpdate('cascade');
$table->timestamps();
});
}
public function down()
{
DB::statement('SET FOREIGN_KEY_CHECKS = 0');
Schema::dropIfExists('user_badge');
DB::statement('SET FOREIGN_KEY_CHECKS = 1');
}
}
in your badge query you need to specify the table since you're using whereHas
$badge = Badge::whereHas('users', function ($query) use ($request){
$query->where('users.id' , $request['user_id']);
})
->where('badgecategory_id',$request['badgecategory_id'])
->first();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.