【问题标题】:How to establish polymorphic relations with Eloquent如何用 Eloquent 建立多态关系
【发布时间】:2020-07-24 23:21:00
【问题描述】:

使用 Laravel 和 Eloquent。我有一个如下所示的数据库:

dance_performers.dance_perfomer_type 字段包含 '\App\Dancer''\App\Couple''\App\Formation' 等值。

您将如何继续将dance_performers.dance_perfomer_id 连接到不同的型号?我不确定我应该如何在不同的模型中编写关系。 我是否应该创建一个 \App\Performer 模型,然后将其定向到前面提到的三个模型之一?

使用多态关系:

class Dance extends Model {
    public function couples() {
        return $this->morphedByMany('\App\Couple', 'dance_performer');
    }
}

class Couple extends Model
{   
    public function dances() {
        return $this->morphToMany('App\Dance', 'dance_performer');
    }
}

目前,$dances = \App\Dance::with('couples')->get(); 仅返回空关系。 我将不胜感激。

【问题讨论】:

  • 查看我的答案会解决你的问题

标签: php laravel eloquent orm model


【解决方案1】:

根据您的代码,一切都是正确的。我猜你在数据库中没有正确的数据。 添加如下数据并检查。

dances

id - 1,名称 - 'Dance A'

id - 2,名称 - 'Dance B'

couples

id - 1, name - '情侣 A'

id - 2, name - '情侣 B'

dance_performers

id - 1,dance_id - 1,dance_performer_type - '\App\Couple',dance_performer_id - 1

id - 2,dance_id - 2,dance_performer_type - '\App\Couple',dance_performer_id - 2

【讨论】:

  • 感谢您抽出宝贵时间。我再次检查了记录,它们看起来确实不错。也许值得一提的是,情侣和编队与舞者之间存在多对多的关系。我已经用我的数据库的图形表示更新了我的帖子。
【解决方案2】:

解决了。 type 字段应该是 App\ModelName 而不是 \App\ModelName

【讨论】:

    猜你喜欢
    • 2022-01-24
    • 2021-02-06
    • 2015-11-10
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    相关资源
    最近更新 更多