Laravel - BelongsToMany 仅检索当前相关记录

问题描述 投票:0回答:1

我有两个模型,

Ricetta
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');
    }

因此,通过这个查询我可以检索

Ingrediente
中的所有
Ricetta
:

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

它有效,但在

$result->ricetta
中,我拥有所有
Ricetta
Ingredinte
,而不仅仅是当前的
Ricetta
(id = 1)。

如何修改查询以仅检索当前的 Ricetta?

谢谢!

laravel
1个回答
0
投票

您可以在加载每个关系时将约束传递给它们:

$result = $model->newQuery()
    ->select('ingrediente.*')
    ->with([
        'ricetta' => static function($query) {
            $query->where('ricetta.id', 1);
        }
    ])
    ->get();
© www.soinside.com 2019 - 2024. All rights reserved.