Laravel如何变身为许多作品? [英] How does Laravel morph to many work?

查看:71
本文介绍了Laravel如何变身为许多作品?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有一个多对多关系.项目可以有几个小时,其他表也可以有几个小时.

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'
    );
}

这种方法有效,但是我不明白为什么.为什么我必须写两次"owner_type"作为参数?

And this methods works, but I don't understand why. Why do I have to write 'owner_type' twice as a parameter?

推荐答案

简单的答案是:您没有.

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.

第一个参数是相关类.第二个参数是关系的名称".第三个参数是要使用的类型"字段.第四个参数是要使用的"id"字段.

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');
}

如果您未指定类型"或"id"字段,它将使用给定的名称"(第二个参数),并分别附加"_type"和"_id".如果指定类型"和标识"字段,则根本不使用名称"参数.

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.

这篇关于Laravel如何变身为许多作品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆