gpt4 book ai didi

php - 如何在 Laravel 中创建数据透视表

转载 作者:搜寻专家 更新时间:2023-10-31 20:57:31 24 4
gpt4 key购买 nike

我有一个正在创建的赞助应用程序,并试图让一个数据透视表在我的用户和 child 之间工作,但是当我有一个用户赞助一个 child 时,数据透视表 kid_user 没有被填充使用 kid_iduser_id。不确定我错过了什么。

  • 一个 child 可以拥有尽可能多的用户(赞助商),因为他们的插槽允许他们。
  • 用户可以赞助一个 child 、多个 child 或同一个 child 多次如果需要的话。

这是我的 kid_user 数据透视表:

public function up()
{
Schema::create('kid_user', function (Blueprint $table) {
$table->integer('kid_id')->unsigned()->index();
$table->foreign('kid_id')->references('id')->on('kids')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->primary(['kid_id', 'user_id']);
});
}

然后在用户模型上:用户可以有很多 child ......

public function kid()
{
return $this->hasMany(Kid::class);
}

然后在 Kid 模型上: children 可以有很多用户...

  public function user() {
//return $this->belongsTo(User::class); (Tried this..)
return $this->hasMany(User::class);
}

这是我正在使用的表格。(表格中仅包含相关信息)

+---------------------+
| Tables_in_Database |
+---------------------+
| kid_user |
| kids |
| users |
+---------------------+

+-----------------------------+
| users table |
+----+------------+-----------+
| id | first_name | last_name |
+----+------------+-----------+
| 1 | John | Smith |
| 2 | Jane | Doe |
+----+------------+-----------+

+-----------------------------+
| kids table |
+----+------------+-----------+-------+
| id | first_name | last_name | slots |
+----+------------+-----------+-------+
| 1 | Bobby | Little | 3 | -> Can be sponsored 3 times
+----+------------+-----------+-------+

+--------------------+
| kid_user table | THE BELOW RESULTS ARE WHAT I'M LOOKING FOR.
+--------------------+
| *kid_id | *user_id | * = Primary Key
+---------+----------+
| 1 | 1 | -> Sponsored 1st Slot
+---------+----------+
| 1 | 2 | -> Sponsored 2nd Slot
+---------+----------+
| 1 | 1 | -> Sponsored 3rd Slot
+---------+----------+

因此,当用户赞助一个 child 时。我想将 kid_iduser_id 输入到 kid_user 数据透视表中。任何帮助将不胜感激。

最佳答案

首先,您可能想以复数形式重命名模型中的函数,因为它没有一个,而是多个关系。

所以在你的用户模型中添加这个:

public function kids()
{
return $this->belongsToMany(Kid::class);
}

在您的 Kid 模型中:

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

然后为了保存到数据透视表,因为你的表命名是正确的,只需做:

$user->kids()->attach($kid);

将其正确保存在数据透视表中。首先确保您有现有的 User 和 Kid 作为变量。更多详情 here

关于php - 如何在 Laravel 中创建数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54153547/

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