eloquent - How does Laravel morph to many work? -


i have morph-to-many relation in app. items can have hours , other tables can have hours.

so have method declaring relation between items , hours:

public function hours() {     return $this->morphmany(         hoursetitemhourtable::class,         'owner_type',         'owner_type',         'owner_id'     ); } 

and methods works, don't understand why. why have write 'owner_type' twice parameter?

short answer is: don't.

actually, reason method working have written because you've specified third , fourth parameters.

the first parameter related class. second parameter "name" of relationship. third parameter "type" field use. fourth parameter "id" field use.

only first 2 parameters required. second parameter used build field names access, when not provided in third , fourth parameters.

basically, can write relationship this, , work fine:

public function hours() {     return $this->morphmany(hoursetitemhourtable::class, 'owner'); } 

if don't specify "type" or "id" field, take "name" given (second parameter), , append "_type" , "_id", respectively. if specify "type" , "id" fields, "name" parameter not used @ all.


Comments