Answer the question
In order to leave comments, you need to log in
The filter does not work correctly, all products are pulled out, even if the authors are not attached. What is the best way to make a filter?
I want to make a filter, a many-to-many relationship
. Products are linked to categories, their authors are linked to certain products (There may be several of them)
in json I want to display a collection of products with selected authors,
for example:
a filter is made for 1 category, the id of the author of the product is selected in the filter, for example 1 or 1 and 2, etc.
and you need to display the category itself + only products that have authors from the filter
, for some reason I pull out all the products
public function filter($category)
{
$sortDirection = 'desc';
$tags = ['1','2'];
return CategoryResource::collection(Category::with(['products.authors' => function ($query) use ($sortDirection,$tags) {
$query->whereIn('user_id', $tags)->orderBy('id', $sortDirection);
}])
->where('id',$category)
->get());
}
public function products() {
return $this->hasMany(Product::class);
}
public function authors() {
return $this->belongsToMany(User::class,'product_user','product_id');
}
"id": 2,
"name": "Категория 1 ",
"count": 2,
"products": [
{
"id": 2,
"name": "Товар 1",
"description": "Описание",
"authors": [
{
"id": 1,
"firstname": "Ivanov 1",
"lastname": "Ivanov 1",
},
{
"id": 2,
"firstname": "lan",
"lastname": "lanov",
}
]
},
{
"id": 2,
"name": "Товар 2",
"description": "Описание",
"authors": []
}
]
$tags = ['1'];
"id": 2,
"name": "Товар 1",
"description": "Описание",
"authors": [
{
"id": 1,
"firstname": "Ivanov 1",
"lastname": "Ivanov 1",
},
Answer the question
In order to leave comments, you need to log in
The with method does not filter data - it only filters relationships
. To get the data you need, you need to use whereHas
with(['products' => function ($query) use ($sortDirection, $tags) {
$query->whereHas('authors' ,function ($q) use ($tags) {
$query->whereIn('user_id', $tags);
})->orderBy('id', $sortDirection);
}])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question