Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent Relationships findMany or find

If you have two models Post and Comment, and in the Comment model you have defined a belongsTo(), relationship called posts, I know that it is possible to do this:

App\Comment::find(1)->posts()->where('category', 3)->get()

But what I want is to pass more than one primary key id to the method find like:

App\Comment::find([1,2,3])->posts()->where('category', 3)->get()

Or

App\Comment::findMany([1,2,3])->posts()->where('category', 3)->get()

These two gives me the error method posts does not exist. So how else can I handle this problem?

like image 545
Phillis Peters Avatar asked Oct 30 '22 18:10

Phillis Peters


1 Answers

When you're using find() method, you get a model, but findMany() returns a collection.

What you probably want is this:

App\Comment::whereIn('id', [1, 2, 3])->with(['posts' => function($q) {
    $q->where('category', 3);
}])->get();
like image 126
Alexey Mezenin Avatar answered Nov 09 '22 13:11

Alexey Mezenin