vendredi 23 mars 2018

How to get next and previous records from a model with a parent child relationship

I have a parent child relationship in my model where a Section can have many subsections. so in my model I have joined the table onto itself and using a parent column I can determine which section is a parent / child.

My question is how would I retrieve the next and previous records for the subsections?

My Section model:

    class Section extends Model
    {
        use BelongsToSortedManyTrait, SortableTrait;


        public $fillable = [
            'id',
            'name',
            'description',
            'parent',
            'position'
        ];


        public function subsections() {
            return $this->hasMany(self::class, 'parent')->sorted();
        }

       public function next(){
        // get next record
        return self::where('id', '>', $this->id)->orderBy('id','asc')->first();

       }

       public  function previous(){
        // get previous record
        return self::where('id', '<', $this->id)->orderBy('id','desc')->first();

    }

    }

Notice the previous and next methods, at the moment they will work for all sections but won't take into account the parent / child relationship.

Any way I can achieve this?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire