Skip to content

Instantly share code, notes, and snippets.

@aquasmit
Last active August 23, 2021 04:00
Show Gist options
  • Save aquasmit/e0edae8b24fad18a4ddf3957c79cfd0d to your computer and use it in GitHub Desktop.
Save aquasmit/e0edae8b24fad18a4ddf3957c79cfd0d to your computer and use it in GitHub Desktop.
Laravel - Eloquent - query many to many relationship

Laravel - Eloquent - query many to many relationship

Example:

Table 1: posts

Table 2: categories

Pivot Table: category_post with foreign keys category_id, post_id

Model File: Post.php

.....
public function categories()
{
    return $this->belongsToMany('App\Categories','category_post','post_id','category_id');
}

Model File: Category.php

.....
    public function posts()
    {
        return $this->belongsToMany('App\Posts','category_post','category_id','post_id');
    }    

Eloquent in Controller

So below Eloquent will fetch 5 records where categoty_id = 11

.....
     		$posts = Posts::whereHas('categories', function($q) use($slug){

    			               $q->where('id', 11); //this refers id field from categories table

		             })
                 ->where('type','post')
                 ->where('active',1)
                 ->orderBy('post_date','desc')
                 ->paginate(5);
@danielchikaka
Copy link

Thanks!

Where can i get a clear in depth explanation of what eloquent queries can do?

@vanbaodo
Copy link

Hi, Where can i get a clear in depth explanation of what eloquent queries can do? I don't understant

@olivsinz
Copy link

olivsinz commented May 15, 2020

Thank you very much
I have this errors with laravel 7

Illuminate\Database\QueryException SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous

My solution to fix it was :

 $posts = Posts::whereHas('categories', function($q) use($slug){
                         $q->where('categories.id', 11); //this refers id field from categories table

		     })
                    >where('type','post')
                   ->where('active',1)
                   ->orderBy('post_date','desc')
                   ->paginate(5);

@mcanepa
Copy link

mcanepa commented Aug 15, 2020

just what I needed. Thanks!

@mahdihassani12
Copy link

How to pass categories.id to the function:
$posts = Posts::whereHas('categories', function($q) use($slug){
$q->where('categories.id', 11); //How to pass this id inside function?

	     })
                >where('type','post')
               ->where('active',1)
               ->orderBy('post_date','desc')
               ->paginate(5);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment