John Davidson

php - How to properly retrieve and store self referencing table relationship in Laravel?

0 comments
Message:


Hi i'm just started to learn laravel and i have 2 database tables that i want to modify, the first one is the main table which is products and the other table is upsells which will connect two entity from products table:


products






































id name price
1 Bag 300
2 Belt 100
3 ring 120
4 Hat 250
5 Scarf 125


My Answer:
upsells




id
product_id
upsell_product_id




1
1
2


2
1
3


3
2
4


4
3
5


5
4
1


6
5
2



To properly retrieve and store self-referencing table relationship in Laravel, you can use Eloquent relationships.

First, you need to define the relationships in your Product model. In the Product model, you can define a method to retrieve the upsell products:

php
public function upsells()
{
return $this->belongsToMany(Product::class, 'upsells', 'product_id', 'upsell_product_id');
}


Next, you can retrieve the upsell products for a specific product like this:

php
$product = Product::find(1);
$upsells = $product->upsells;


To store a new upsell relationship, you can use the attach method:

php
$product = Product::find(1);
$upsellProduct = Product::find(2);
$product->upsells()->attach($upsellProduct);


This will create a new row in the upsells table linking product 1 with product 2.

I hope this helps! Let me know if you have any other questions.

Rate this post

4 of 5 based on 7773 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us