Leonardo Beal Leonardo Beal - 1 month ago 25
PHP Question

How to retrieve grandchildren through a polymorphic relation in Laravel 5.2?

My database design looks like the below diagram.

A course has many modules
Modules morphs to Scorm and other 2 tables (not used in this example)
A scorm Morph one Module and has Many Scoes
I am trying to access from my course model all the scoes related using:

$course->scoes.


I am using Laravel 5.2, using the Eloquent relations I know this is not possible. After few tests, using the query builder I actually can return the correct data, but, they come back as being an instance of Module::class instead of Scorm, and Sco.

This is the code I have now.

Thanks,

public function modules() {
return $this->hasMany(Module::class);
}

public function scorms(){
return $this->modules()->where('moduleable_type','=','scorms');
}
public function scoes(){
return $this->scorms()->select('scoes.*')
->join('scoes','modules.moduleable_id','=','scoes.scorm_id');
}


enter image description here

Answer

I found a way to do what I was trying to do. This way makes only 2 queries to the db and it's located in the Sco Model.

//returns a Course Object.
$sco->course()

/**
* Get the course
* @return App\Course|null
*/
public function Course(){
   $o = $this
        ->join('scorms','scoes.scorm_id','=','scorms.id')
        ->join('modules',function($join){
            $join
                ->on('moduleable_id','=','scorms.id')
                ->where('moduleable_type','=','scorms');
        })
        ->join('courses','modules.course_id','=','courses.id')
        ->select('courses.id as course_id')
        ->first();

    if(!$o) return null;

    return Course::find($o->course_id);

}
Comments