samedi 16 juin 2018

Laravel get MySQL to query Builder statement in Eloquent model

Given the following table:

+----+----------+------------+ | id | parent_id| Name | +----+----------+------------+ | 1 | NULL | Parent 1| | 2 | 1 | Child 1| | 3 | 1 | Child 2| | 4 | 1 | Child 3| | 5 | NULL | Parent 2| | 6 | 1 | Child 4| | 7 | 1 | Child 5| | 8 | 1 | Child 6| +----+----------+------------+

I want to select the same data, even if the provided ID is a parent or not. So the provided ID = 1 (parent) or if the ID = 3 (child) I want to select this exact same data:

+----+----------+------------+ | id | parent_id| Name | +----+----------+------------+ | 1 | NULL | Parent 1| | 2 | 1 | Child 1| | 3 | 1 | Child 2| | 4 | 1 | Child 3| +----+----------+------------+

I have a working MySQL query for it:

SELECT * FROM packages

WHERE id = 3 

OR parent_id = 3 

OR parent_id = (SELECT parent_id FROM packages WHERE id = 3)

OR id = (SELECT parent_id FROM packages WHERE id = 3)

So if you replace 3 with 1 you get the same results as expected.

I have already the following function in my Package Model:

<?php

public function related()
{
    $childParent = Package::select( 'parent_id' )->where( 'id', $this->id )->first();

    $query = $this->where( 'id', $this->id )
                  ->orWhere( 'parent_id', $this->id );

    if ( null !== $childParent->parent_id ) {
        $query
            ->orWhere( 'parent_id', $childParent->parent_id )
            ->orWhere( 'id', $childParent->parent_id );
    }

    return $query;
}

But this feels... well... ugly. I am coming from Symfony where this kind of queries can get easily build (and with little codelines) with the ORM query builder.

Are I am missing a feature in Laravel Eloquent to make this nice and short?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire