简体   繁体   English

如何向 pivot 表多对多添加额外列

[英]How to add extra column to pivot table many to many

I have simple items table.我有简单的items表。

Example:例子:

Paper.纸。 Made from bamboo and cotton (if google does not lie).由竹子和棉花制成(如果谷歌没有说谎的话)。

Also, a book made from paper.还有,纸做的书。

So paper parent of bamboo and cotton also child of book.故竹棉之纸父,亦书之子。

I think I can explain my table structure in two words.我想我可以用两个词来解释我的表结构。

And now my code.现在我的代码。 All of this code examples and table structures simplified as much as possible.所有这些代码示例和表结构都尽可能地简化。

items

╔════╦═══════════════╦══════╗
║ id ║  name         ║ price║
╠════╬═══════════════╬══════╣
║  1 ║ Book          ║ 500  ║
║  2 ║ Paper         ║  50  ║
║  3 ║ Bamboo        ║  15  ║
║  4 ║ Cotton        ║  7   ║
╚════╩═══════════════╩══════╝

item_item table (many to many) item_item表(多对多)

╔════╦═══════════════╦══════════╗
║ id ║  item_id      ║ parent_id║
╠════╬═══════════════╬══════════╣
║  1 ║     2         ║    1     ║
║  2 ║     3         ║    2     ║
║  3 ║     4         ║    2     ║
╚════╩═══════════════╩══════════╝

Model Item Model Item

class Item extends Model
{
    protected $fillable = ["name", "price"];

    public $timestamps = false;

    public function components()
    {
        return $this->belongsToMany('App\Models\Item', "item_item", "parent_id", "item_id");
    }
}

ItemController create项目控制器创建

 public function store(Request $request)
    {
        $request->validate([
            "name" => "required",
            "price" => "required",
        ]);

        $item = Item::create([
            "name" => $request->name,
            "price" => $request->price,
        ]);

        $item->components()->attach($request->items);


        return redirect()->route("items");
    }

Update with sync:同步更新:

$item->components()->sync($request->components);

And my view而我的看法

<div class="form-group">
    <label for="item">Choose child items</label>
    @foreach ($items as $item)
        <div class="checkbox">
            <label ><input class="mr-2" name="items[]" type="checkbox" value="{{ $item->id }}"/>{{ $item->name }}</label>
        </div>
    @endforeach
</div>

This is work fine, but the question is how to add column item_count to pivot table item_item .这很好,但问题是如何将列item_count添加到 pivot 表item_item For count how many items need to be create something.计算需要创建多少项目。

For example 500 papers to create a book例如 500 篇论文创建一本书

I try to do like in this video but doesn't work.我试着在这个视频中做类似的事情,但没有用。

change table name and class to diffrance name like books, authors then you can use book_id with author_id将表名和 class 更改为 diffrance 名称,如书籍,作者,然后您可以使用 book_id 和 author_id

class book {
      public function author(){
         return $this->belongsTo(App\Models\Author,'id','author_id');
      }
}

referrance Laravel Eloquent: Relationships参考Laravel Eloquent:关系

Example:例子:

table structure like so:表结构如下:

items id - integer price - integer商品编号 - integer 价格 - integer

parents id - integer name - string父母 id - integer 姓名 - 字符串

childs item_id - integer parent_id - integer孩子 item_id - integer parent_id - integer

Model Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    public function parent()
    {
        return $this->belongsTo(Child::class, 'id', 'item_id');
    }
}

Suggest建议

you can use parnt_id in items table您可以在项目表中使用 parnt_id

Schema::create('items', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->integer('parnt_id');
    $table->integer('price');
    $table->timestamps();
});

I assume, you can create a migration to update your pivot table structure.我假设,您可以创建一个迁移来更新您的 pivot 表结构。

Then, You can change your然后,您可以更改您的

$item->components()->attach($request->items);

to

$item->components()->attach($request->items, [item_count]);

in document在文档中

When attaching a relationship to a model, you may also pass an array of additional data to be inserted into the intermediate table:将关系附加到 model 时,您还可以传递要插入中间表的附加数据数组:

$user->roles()->attach($roleId, ['expires' => $expires]);

and

sync as同步为

$item->components()->sync([$request->items, $item_count]);

in document在文档中

You may also pass additional intermediate table values with the IDs:您还可以使用 ID 传递其他中间表值:

$user->roles()->sync([1 => ['expires' => true], 2, 3]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Laravel - 使用额外列保存到多个与多个关系的数据透视表 - Laravel - Saving to pivot table in many to many relationship with extra column 如何通过 pivot 表中的列过滤多对多关系 - How to filter a many to many relationship by a column in pivot table Laravel 5.x,其中有许多附加的枢轴列 - Laravel 5.x whereHas many-to-many with an extra pivot column 如何通过 laravel 中的复选框向 pivot 表添加额外的列 - how to add an extra column to pivot table via checkbox in laravel 多对多关系在Laravel中检索连接到数据透视表的列 - Many to many relationship retrieve a column connected to pivot table in Laravel Laravel 5.3多态多对多-如何获取所有相关行,而不管其表是否按数据透视表列排序? - Laravel 5.3 Polymorphic many to many - how to get all the related rows regardless of their table sorted by pivot column? Laravel 5.8:如何在多对多关系中显示数据透视表的列信息 - Laravel 5.8: How to show a column information of a pivot table in Many To Many relationship 如何在多对多的Laravel数据透视表中停止自动排序 - How to stop auto sorting in laravel pivot table of many to many realtion 如何批量更新 Pivot 表以获取 Laravel 中的相同属性 多对多 - How To Bulk Update Pivot Table For Same Attributes In Laravel Many To Many 如何访问数据透视表的数据(多对多关系laravel) - How to access data of a pivot table ( many to many relationship laravel )
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM