gpt4 book ai didi

mysql - 允许 Laravel ManyToMany 迁移具有多个相同的组合

转载 作者:行者123 更新时间:2023-11-29 16:15:29 25 4
gpt4 key购买 nike

我在 Laravel 中遇到了 ManyToMany 关系的问题。

我有表 A 和表 B,并有一个数据透视表来连接它们。当我尝试将 A 和 B 附加一些自定义数据透视表数据时,它工作得很好。但是,一旦我尝试使用一些不同的数据透视数据在 A 和 B 之间建立另一个连接,它要么给我一个错误,表明表已经连接,要么只是给表提供了相同的 ID,这弄乱了我的整个网站。

看起来 $table->increments('id'); 没有做任何事情,因为即使我删除它,表仍然有一个 id 字段,它似乎是一个组合A 和 B ID。

我希望能够通过自定义/唯一的数据透视数据在 A 和 B 之间建立大量连接。

名为赏金的表具有以下架构构建器

$table->increments('id');
$table->boolean('enable');
$table->char('name');
$table->char('slug');
$table->timestamps();

名为users的表B具有以下内容

$table->increments('id');
$table->boolean('enable');
$table->char('name');
$table->char('slug');
$table->timestamps();

名为bounty_user表的连接枢轴设置如下

$table->increments('id');

$table->json('user_data')->nullable();

$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

$table->unsignedInteger('bounty_id');
$table->foreign('bounty_id')->references('id')->on('bounties')->onDelete('cascade');

$table->timestamps();

我的用户模型

class User extends Authenticatable
{
use HasApiTokens, Notifiable;


public function bounties()
{
return $this->belongsToMany('App\Bounty')
->withPivot('user_data', 'state')->using('App\BountyPivotCasting')
->withTimestamps();
}
}

以及赏金模型

class Bounty extends Model
{
use Sluggable;

public function sluggable()
{
return [
'slug' => [
'source' => 'name'
]
];
}

public function users()
{
return $this->belongsToMany('App\User')
->withPivot('user_data', 'state')->using('App\BountyPivotCasting')
->withTimestamps();
}
}

最佳答案

在你的表模型中确保你有这个

赏金模型

public function users()
{
return $this->belongsToMany(User::class, 'bounty_user');
}

用户模型

public function bountie()
{
return $this->belongsToMany(Bountie::class, 'bounty_user');
}

然后使用同步来附加和分离例如:$user->bountie()->sync(bountie_id)

关于mysql - 允许 Laravel ManyToMany 迁移具有多个相同的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54842126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com