问题
I have a morph-to-many relation in my app. items can have hours and other tables can also have hours.
So I have a method for declaring a relation between Items and Hours:
public function hours()
{
return $this->morphMany(
HoursetItemHourTable::class,
'owner_type',
'owner_type',
'owner_id'
);
}
And this methods works, but I don't understand why. Why do I have to write 'owner_type' twice as a parameter?
回答1:
Short answer is: you don't.
Actually, the only reason the method is working as you have it written is because you've specified the third and fourth parameters.
The first parameter is the related class. The second parameter is the "name" of the relationship. The third parameter is the "type" field to use. The fourth parameter is the "id" field to use.
Only the first two parameters are required. The second parameter is used to build the field names to access, but only when they are not provided in the third and fourth parameters.
Basically, you can write your relationship like this, and it will work fine:
public function hours()
{
return $this->morphMany(HoursetItemHourTable::class, 'owner');
}
If you don't specify the "type" or the "id" field, it will take the "name" given (second parameter), and append "_type" and "_id", respectively. If you specify the "type" and "id" fields, the "name" parameter is not used at all.
来源:https://stackoverflow.com/questions/35080029/how-does-laravel-morph-to-many-work