Issue
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
Solution
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();
Answered By - Marwane Ezzaze Answer Checked By - Cary Denson (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.