Fahad Imtiaz
Fahad Imtiaz

Reputation: 29

laravel has many through piviot table

I have 3 tables

    Products
    id, name, image
    Offers
    id,name
    Offer_product
    id,offer_id,product_id

I am accessing data of product table with pagination using

$list  = Product::query()->paginate(6);

now i want the complete record of products with offer name stored in offers table . id of both product and offers are stored in offer_product table where one products can have many offers

Upvotes: 1

Views: 62

Answers (1)

KeitelDOG
KeitelDOG

Reputation: 5180

In your DB design you have a Many-to-Many relation, which in Laravel is handle by belongsToMany https://laravel.com/docs/5.7/eloquent-relationships#many-to-many.

hasManyThrough is for cascade 1-to-Many -> 1-to-Many case. Let's say an Artist has many Albums and each Album has many Songs, then an Artist has many Songs through Albums. If you need an Artist Songs, then you may use directly hasManyThrough.

In your case your relation in Product.php model should be :

public function offers() {
    return $this->belongsToMany(Offer::class, 'Offer_product')->withPivot('id');
}

In Offer.php model :

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

Now if you want all of them with eager loading https://laravel.com/docs/5.7/eloquent-relationships#eager-loading to avoid N(products)+1 calls to database :

$products = Product::with('offers')->get();
foreach ($products as $product) {
    echo 'product : '.$product->name.'<br/>';
    foreach($product->offers as $offer) {
        echo '<br>---- offer : '.$offer->name;
        // once you called the relation, then you can access data on pivot table
        echo ' - pivot id :'.$offer->pivot->id;
    }
}

Upvotes: 1

Related Questions