Ad

How To Create Relationship Between Three Table In Laravel?

- 1 answer

i have three table:

Suppliers

id | name | type

1  | Test1 | Seller

2 | Test2 | Manufacturer

Products

id | name

1 | product1

2 | product2

Prices

id | supplier_id | product_id | price

1 | 1 | 1 | 1000

2| 2 | 1 | 2000

each supplier have many products and each products belong to many suppliers. Now each supplier can have a separate price for each product.

i have a question that how to create model and table for this scenario?

Ad

Answer

You will have two tables with models:

Product and Supplier

Within /Database/Migrations create_products table:

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

create_suppliers table:

Schema::create('suppliers', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('type');
    $table->timestamps();
});

You will need a pivot table, so create it with Artisan command:

php artisan make:migration create_product_supplier_table

A quick note: Pivot names should be in alphabetical order to fit laravel name convention. 'P' letter comes first and then 'S' (product_supplier) in this case.

product_supplier table:

Schema::create('product_supplier', function (Blueprint $table) {
    $table->id();
    $table->unsignedBigInteger('product_id');
    $table->unsignedBigInteger('supplier_id');
    $table->integer('price');
    $table->timestamps();
});

Now, you will need the following relation declarations in two models

Within App\Product class:

protected $guarded = [];

public function suppliers()
{
    return $this->belongsToMany(Supplier::class)->withPivot('price');
}

And also in App\Supplier class:

protected $guarded = [];

public function products()
{
    return $this->belongsToMany(Product::class)->withPivot('price');
}

You set it up now. Let's give it a try:

$supplier = App\Supplier::create(['name' => 'supplier1', 'type' => 'seller']);
$product = App\Product::create(['name' => 'product1']);

$supplier->products()->attach($product, ['price' => 80]);

Call it back:

$supplier->products; // it will give you the products that attached to supplier.

So, the any supplier can have any product with any price tag.

Ad
source: stackoverflow.com
Ad