Stefan
Stefan

Reputation: 37

Laravel 5.6 filter parent rows based on children

My database structure looks like this (I'm using MySQL):

products:

#------#---------#
| id   | int     |
#------#---------#
| name | varchar |
#------#---------#

products_properties:

#-------------#-----#
| product_id  | int |
#-------------#-----#
| property_id | int |
#-------------#-----#

properties:

#-------#---------#
| id    | int     |
#-------#---------#
| name  | varchar |
#-------#---------#
| value | varchar |
#-------#---------#

Is it possible to filter the product objects based on properties? At I'm trying to use eager loading like this:

$products = Product::with(['properties' => function($query){
    $query->where('name', 'testproperty');
}])
->get();

But when running this code eloquent only filters on the properties found in each product and still finds all the products even when no properties match my where. Also eloquent filters the properties in my product while I want to show all of my properties.

My current outcome is like this:

{
    id: 1,
    name: "test",
    properties: [
        {
            id: 1,
            name: "testproperty",
            value: "testvalue"
        }
    ]
    },
    {
    id: 2,
    name: "test2",
    properties: [

    ]
}

But I'm looking for something like this:

{
    id: 1,
    name: "test",
    properties: [
        {
            id: 1,
            name: "testproperty",
            value: "testvalue"
        },
        {
            id: 2,
            name: "testproperty2",
            value: "testvalue2"
        }
    ]
    }
}

Is it possible to just filter the parent class based on the children objects (properties) and still get all the properties associated with the product?

Upvotes: 1

Views: 2457

Answers (1)

M Khalid Junaid
M Khalid Junaid

Reputation: 64486

I guess you need whereHas to check for child collection

$product = Product::with('properties')
                  ->whereHas('properties', function ($query) {
                       $query->where('name', '=', 'testproperty');
                 })->where('id', $id)->first();

Upvotes: 2

Related Questions