Asfos22
Asfos22

Reputation: 319

How to get data from third table in eloquent relationships eloquent many to many relationship

I am using Eloquent ORM and I have Book model which connect to BookCategory model and BookCategory connect to Category. The l'm problem facing is how to include data from third table in eloquent relationships?

Book
    id
    name
    
Category 
    id
    name
    type
    
BookCategory 
    id
    book_id
    category_id

Upvotes: 1

Views: 1069

Answers (2)

Marwane Ezzaze
Marwane Ezzaze

Reputation: 1057

Lets say for example you want to get all the books of a certain category: assuming your pivot table name is Book_Category in your Category model:

public function books()
{
    return $this->belongsToMany('App\Models\Book', 'Book_Category', 'category_id', 'book_id');
}

and you can eager load category books like :

$categories = Category::get()->load('books');
//OR
$categories = Category::with('books')->get();

Upvotes: 1

Ma Kobi
Ma Kobi

Reputation: 894

If I understand you right, you are looking for the pivot attribute. This makes additional columns of the intermediate table available.

https://laravel.com/docs/8.x/eloquent-relationships#retrieving-intermediate-table-columns

Upvotes: 0

Related Questions