PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, November 15, 2022

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

 November 15, 2022     eloquent, laravel, laravel-5, laravel-6, laravel-7     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing