【问题标题】:How to store array of ids in pivot table?如何在数据透视表中存储 ID 数组?
【发布时间】:2020-01-23 07:24:59
【问题描述】:

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

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

对于我的问题,我需要将category_name(上图)存储在categories 表中,然后将child_name 存储在children 表中,最后存储category_name 的id 和@987654331 的id @在category_child

类别模型中的关系:

public function children()
{
    return $this->belongsToMany('App\Models\Child')->withTimestamps();
}

子模型中的关系:

  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


    【解决方案1】:

    我认为您错过了那里的多对多关系,因为孩子不能属于许多父母!每个孩子都有一个父母,因此该类别应该有很多孩子,但每个孩子必须属于一个类别。我想是的。

    不管怎样,试试这个:

    
        $category = Category::create([
            'category_name' => $request->category_name,
        ]);
    
        $children_id = [];
    
        foreach($request->child_name as $child){
    
            $children_id[] = Child::create([ 'child_name' => $child ])->id;
        }
    
        $category->children()->attach($children_id);
    
    

    【讨论】:

    • 谢谢哥们!!意味着这是与他的孩子创建类别的错误方式?
    【解决方案2】:

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

    【讨论】:

    • 怎么可能?!!!并且已经像您在两个模型中键入但没有存储在数据透视表中一样!
    • @Ahmed 你是什么意思?
    • 请检查我的更新,我在模型中有这些关系,但是当我添加数据透视表时,即使我添加到两个表也是空的!
    猜你喜欢
    • 2020-09-01
    • 2020-07-29
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 2021-08-29
    • 2019-04-07
    • 1970-01-01
    • 2021-02-06
    相关资源
    最近更新 更多