错误的SQL查询与laravel关系



以下是我的表格

Schema::create('badge_user', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
$table->foreignId('badge_id')->references('id')->on('badges')->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
$table->softDeletes();
});
Schema::create('badges', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description')->nullable();
$table->string('image')->nullable();
$table->integer('condition');
$table->timestamps();
$table->softDeletes();
});

这是关系在BagdeUser模式

public function badge()
{
return $this->hasMany(Badge::class);
}

在徽章模式

public function badgeUser()
{
return $this->belongsTo(BadgeUser::class , 'badge_id');
}

In my resource

我已经从badge_user表中获取了所有数据,并将其传递给资源

public function toArray($request)
{
return [
'badges' => new BadgeResource($this->badge),
];
}

BadeResource

public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'description' => $this->description,
'image' => new MediaResource($this->getMedia('badge')->first()),
'condition' => $this->condition,
];

在获取数据时得到这个

Column not found: 1054 Unknown column 'badges.badge_user_id' in 'where clause' (SQL: select * from `badges` where `badges`.`badge_user_id` = 1 and `badges`.`badge_user_id` is not null and `badges`.`deleted_at` is null)

现在我想让徽章与用户

相关联

问题是在你的badge_user迁移时,创建外键badge_id这意味着存在一个关系Badge User N:1 Badge

但是在你的模型中,你分配BadgeUser有许多徽章和徽章属于BadgeUser(这是Badge User 1:N Badge))

这就是为什么laravel正在寻找badge_user_id在query中,因为您以相反的方式定义了关系。

你仍然可能在做M:N关系,你不需要手动做。

你应该使用像这样的东西(来自Laravel文档)

return $this->belongsToMany(Role::class);

最新更新