laravel - 如何在数据透视表中存储 ID 数组?
问题描述
我在这个数组中有这个类别和他的孩子:
现在我有三个表,第一个称为categories
第二个children
,第三个是category_child
在第一个和第二个表之间调用的数据透视表
对于我的问题,我需要将category_name
(在上图中)存储在表categories
中,然后存储child_name
在children
表中,最后存储 idcategory_name
和category_name
incategory_child
类别模型中的关系:
public function children()
{
return $this->belongsToMany('App\Models\Child')->withTimestamps();
}
Child 模型中的关系:
public function category()
{
return $this->belongsToMany('App\Models\Category')->withTimestamps();
}
我的控制器代码:
$category = Category::create([
'category_name' => $request->category_name,
]);
foreach($request->child_name as $child){
Child::create([
'child_name' => $child,
]);
}
$category->children()->attach($child);
return redirect()->back();
此链接中的问题$category->children()->attach($child);
如何存储children
已添加到数据透视表中的 id?
解决方案
您不需要children
直接将它保存在您的数据透视表中,如果您将它存储在您的子表中并且与它有适当的关系,它应该会自动完成。
您需要创建一个数据透视表。迁移方法可能如下所示:
public function up()
{
Schema::create('category_child', function (Blueprint $table) {
$table->unsignedInteger('category_id');
$table->unsignedInteger('child_id');
$table->foreign('category_id')->references('id')->on('category')->onDelete('cascade');
$table->foreign('child_id')->references('id')->on('child')->onDelete('cascade');
});
}
您的模型需要具有以下关系:
class Category extends Model
{
public function users()
{
return $this->belongsToMany('App\User');
}
}
class User extends Model
{
public function categories()
{
return $this->belongsToMany('App\Category');
}
}
推荐阅读
- node.js - 我可以在工作线程中使用节点 http 服务器吗
- javascript - 当我一键调用两个函数(onclick)时,只有重定向函数正在执行。?需要解决方案
- oop - 传递一个对象或传递一个生产该对象的工厂
- python - 为多个元素赋值?
- spring - 使用 @transactional 注释的 Spring Boot Transaction 支持不适用于 mongoDB,有人有解决方案吗?
- c# - 您的 SQL 语法有错误,请查看指定版本的 MYSQL 的手册
- android - 为什么 JetpackCompose Material Theme 的形状与边缘圆度有关?
- android - Android x86 端口 - 更改默认 wifi 的 SSID/BSSID
- c++ - libmodbus 库的 modbus_read_registers() 无法在 Raspbian GNU/Linux 10 (buster) 上读取 RS485 数据,但能够在 Yocto Dizzy Release 上读取
- iso - Etcher 刻录 iso 的更好选择