首页 > 解决方案 > 如何在数据透视表中存储 ID 数组?

问题描述

我在这个数组中有这个类别和他的孩子:

在此处输入图像描述

现在我有三个表,第一个称为categories第二个children,第三个是category_child在第一个和第二个表之间调用的数据透视表

对于我的问题,我需要将category_name(在上图中)存储在表categories中,然后存储child_namechildren表中,最后存储 idcategory_namecategory_nameincategory_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?

标签: laravel

解决方案


您不需要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');
    }
}

推荐阅读