【发布时间】:2021-11-04 21:12:22
【问题描述】:
这是我的桌子
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');
}
在我的资源中
我已经从 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)
现在我希望将徽章与用户关联
【问题讨论】:
-
为什么要使用模型作为数据透视表?
-
那么在没有模型的情况下如何获取数据??
-
数据透视表中的数据与用户和媒体相关,您可以通过使用多对多关系来理解。 laravel.com/docs/8.x/eloquent-relationships#many-to-many你需要知道的所有细节都在里面
标签: mysql laravel eloquent relational-database