Search code examples
laravel

Laravel - BelongsToMany retrieve only current related record


I have two models, Ricetta and Ingrediente and this relationships:

Ingrediente.php

public function ricetta()
    {
        return $this->belongsToMany('\App\Models\Ricetta', 'ricetta_has_ingrediente', 'ingrediente_id', 'ricetta_id')->withPivot('qta', 'unita_misura_id');
    }

Ricetta.php

public function ingrediente()
    {
        return $this->belongsToMany('\App\Models\Ingrediente', 'ricetta_has_ingrediente', 'ricetta_id', 'ingrediente_id')->withPivot('qta', 'unita_misura_id');
    }

So, with this query I can retrive all Ingrediente in Ricetta:

$result = $model->newQuery()
    ->select('ingrediente.*')
    ->with('ricetta')
    ->whereHas('ricetta', function($query){
        $query->where('ricetta_has_ingrediente.ricetta_id', 1);
      })->get();

It works, but in $result->ricetta I have all the Ricetta with the Ingredinte, not only the current Ricetta (with id = 1).

How I can modify the query to retrive only the current Ricetta?

Thanks!


Solution

  • You can pass constraints to each relationship when you load them:

    $result = $model->newQuery()
        ->select('ingrediente.*')
        ->with([
            'ricetta' => static function($query) {
                $query->where('ricetta.id', 1);
            }
        ])
        ->get();