user1875774
user1875774

Reputation: 53

Pull all the fields from both tables in Laravel Many-to-Many relationships

Please any help me that how i pull all the fields from both tables in laravel many to many relationship. I have two table

categories

products

and bridge table

products_to_categories

So i have pull all the fields from both tables based on product id.

Upvotes: 0

Views: 339

Answers (1)

Anatoliy Arkhipov
Anatoliy Arkhipov

Reputation: 691

UPD: As commented patricus, the "bridge" table should be called "category_product"

First, you should define the "belongsToMany" relationship in the Product model:

// ...
class Product extends Eloquent {
    // ...
    function categories() 
    {
        return $this->belongsToMany('Category');
    }
}

After it you should load the product by id:

$product = Product::find($product_id);

And now you can access its categories through the "categories" property:

foreach($product->categories as $category) 
{
    // do what you want with the $category
}

Official docs for M2M relationships: http://laravel.com/docs/4.2/eloquent#many-to-many

Upvotes: 1

Related Questions