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('AppModelsItem', "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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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(AppModelsAuthor,'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 AppModels;

use IlluminateDatabaseEloquentModel;

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();
});

Method 2

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]);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x