samedi 22 septembre 2018

Laravel: Sorting Polymophic Relations

REQUIREMENTS

  1. In the Student Controller, the results must be sorted by student name.

  2. The results must be sorted by student's guardian name.



TABLE STRUCTURE

  • taxonomies

    • id
    • entity_type - It contains the class name of the owning model.
    • entity_id - It contains the ID value of the student.
  • students

    • id
    • name
  • guardians

    • id
    • student_id
    • name



CONTROLLER

  • StudentController.php

    public function getStudents()
    {
        return Taxonomy::with([
                'entity', 
                'entity.guardian'
            ])
            ->where('entity_type', 'Student')
            ->get();
    }
    
    



MODEL

  • Taxonomy.php

    public function entity()
    {
        return $this->morphTo();
    }
    
    
  • Student.php

    public function taxonomies()
    {
        return $this->morphMany('App\Taxonomy', 'entity');
    }
    
    public function guardian()
    {
        return $this->hasOne('App\Guardian');
    }
    
    
  • Guardian.php

    public function student()
    {
        return $this->belongsTo('App\Student');
    }
    
    


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire