lundi 29 octobre 2018

Eloquent manytomany polymorphic nested query withCount

I have the following manytomany polymorphic relationship

Asset

public function countries()
{
    return $this->morphToMany('App\Country', 'locationable');
}

Country

public function assets()
{
    return $this->morphedByMany('App\Asset', 'locationable');
}

Also Category has manytomany with Assets

public function assets()
    {
        return $this->belongsToMany('App\Asset', 'category_asset');
    }

I need to query a category and eager load assets that have country assigned.

Here is my eloquent query

$category = Category::with(['children.assets' => function ($query) {
            $query->whereHas('countries', function($q) {
                $q->where('code', '=', 'FR');
            });
        }])
            ->where('id', 1)
            ->first();

This seems to work, but then when I use the Category model with $this->assets It loads all of them, even if only one is returned in the query.

I am using API resources like so

AssetResource::collection($this->whenLoaded('assets'))

Where can I put a condition to only use assets that passed the condition where('code', '=', 'FR')



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire