Randall
Randall

Reputation: 2858

How to add extra column to pivot table many to many

I have simple items table.

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)

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

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. For count how many items need to be create something.

For example 500 papers to create a book

I try to do like in this video but doesn't work.

Upvotes: 1

Views: 2371

Answers (2)

Prafulla Kumar Sahu
Prafulla Kumar Sahu

Reputation: 9693

I assume, you can create a migration to update your pivot table structure.

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:

$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:

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

Upvotes: 1

Ahmed Yehia
Ahmed Yehia

Reputation: 80

change table name and class to diffrance name like books, authors then you can use book_id with author_id

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

referrance Laravel Eloquent: Relationships

Example:

table structure like so:

items id - integer price - integer

parents id - integer name - string

childs item_id - integer parent_id - integer

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

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

Upvotes: 1

Related Questions