vendredi 15 juin 2018

Laravel get Model siblings and self - is this the right way?

I have a Eloquent model which has these functions:

<?php

class Package extends Model
{

    public function parent()
    {
        return $this->belongsTo( Package::class, 'parent_id' );
    }

    public function childs()
    {
        return $this->hasMany( Package::class, 'parent_id' );
    }

    /**
     * All packages that belongs to each other
     */
    public function siblings_and_self()
    {
        $result = $this->newCollection()->add( $this );
        $result = $result->merge( $this->parent()->get() );
        $result = $result->merge( $this->childs()->get() );

        return $result;
    }
}

It is about the last function siblings_and_self and I am curious if this is the correct way to retrieve the result.

Or would you suggest another method retrieving all related records and self?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire