1
votes

I have a model with relations and I want to return only part of these relations that match a query.

But I don't achieve this, every time every relations are return.

My models are

Lot

public function etageLots()
{
    return $this->hasMany('App\Models\Copro\EtageLot');
 }

EtageLot

public function lot()
{
    return $this->belongsTo('App\Models\Copro\Lot');
}
public function fractions()
{
    return $this->hasMany('App\Models\Copro\Fraction','etage_lot_id');
 }

Fraction

public function etageLot()
{
    return $this->belongsTo('App\Models\Copro\EtageLot','etage_lot_id');
 }
public function type()
{
    return $this->belongsTo('App\Models\Copro\Type');
 }

And Type

public function fractions()
{
   return $this->hasMany('App\Models\Copro\Fraction');
}

And here query that I tried :

$lots2 = Lot::whereHas('etageLots.fractions.type', function ($query)  { 
        $query->where('types.surface_ascenseur','>',0); 
    })
    ->with("etages.coeff")
    ->where('lots.id', '=', 1)
    ->first();
dd($lots2->etageLots->first()->fractions);

(Return every fractions even if types.surface_ascenseur > 0)

$lots2 = Lot::with(['etageLots.fractions.type' => function ($query)  { 
        $query->where('types.surface_ascenseur','>',0); 
    }])
    ->with("etages.coeff")
    ->where('lots.id', '=', 1)
    ->first();
dd($lots2->etageLots->first()->fractions)

(Return every fractions even if types.surface_ascenseur > 0)

$lots2 = Lot::with('etageLots.fractions.type',"etages.coeff")
    ->whereHas('etageLots.fractions.type', function ($q) {
        $q->where('surface_ascenseur','>',0);
      })
    ->where('lots.id', '=', 1)
    ->first();
dd($lots2->etageLots->first()->fractions);

(Return every fractions even if types.surface_ascenseur > 0)

$lots2 = Lot::with(['etageLots.fractions' => function ($query)  { 
        $query->whereHas('type', function ($q) {
            $q->where('surface_ascenseur','>',0);
          });
        }
        ])
    ->with("etages.coeff")
    ->where('lots.id', '=', 1)
    ->first();
dd($lots2->etageLots->first()->fractions)

(Return the right amount of fractions but without 'type' relation and I need it)

How to only return fractions with fractions.type.surface_ascenseur > 0 ?

Thank for your help

1

1 Answers

1
votes

You are very close with the last one. Try:

Lot::with([
        'etageLots.fractions' => function ($query)  { 
            $query->whereHas('type', function ($q) {
                $q->where('surface_ascenseur','>',0);
            })
            ->with('type'); // <- add this!
        }
    ])
    ->with("etages.coeff")
    ->where('lots.id', '=', 1)
    ->first();