How does Laravel morph to many work?

寵の児 提交于 2020-01-06 19:55:54

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!