Diego Alejandro Lopez
Diego Alejandro Lopez

Reputation: 61

Laravel Eloquent - Get results from parents that has only one child

I'm trying to get all results that match a certain child id, and that the parent has only on child. My initial idea its to do it by hand with nested foreachs, but is there any method that does this in a simpler way?

My parent is called Proyectos and then I have a pivot table called PaisBeneficiarioProyecto, and the other parent is PaisBeneficiario. It's a many-to-many relation.

$monto_pais = Proyecto::all()->where('pais_beneficiarios', $id)->sum('monto_aprobado');

The code explained above does what you expect, but it's not the result that I need. Here are my models:

Proyectos:

public function pais_beneficiarios()
    {
        return $this->belongsToMany(\App\Models\PaisBeneficiario::class, 'pais_beneficiario_proyecto', 'id_proyecto', 'id_pais_beneficiario')
                    ->withPivot('monto_beneficio');
    }

PaisBeneficiario:

public function pais_beneficiario()
    {
        return $this->belongsTo(\App\Models\PaisBeneficiario::class, 'id_pais_beneficiario');
    }

    public function proyecto()
    {
        return $this->belongsTo(\App\Models\Proyecto::class, 'id_proyecto');
    }

PaisBeneficiarioProyectos:

public function proyectos()
    {
        return $this->belongsToMany(\App\Models\Proyecto::class, 'pais_beneficiario_proyecto', 'id_pais_beneficiario', 'id_proyecto')
                    ->withPivot('monto_beneficio');
    }

The value that I'm trying to sum is called monto_aprobado which is on Proyectos

Upvotes: 2

Views: 1121

Answers (1)

ako
ako

Reputation: 2136

The below query gives you the sum of monto_aprobado field of Proyecto models that jus have one pais_beneficiarios_count.

Proyecto::withCount('pais_beneficiarios')
    ->having('pais_beneficiarios_count', 1)
    ->sum('monto_aprobado');

Upvotes: 1

Related Questions