如何与口才建立多态关系

时间:2020-07-24 23:21:00

标签: php laravel eloquent orm model

使用Laravel和Eloquent。我有一个看起来像这样的数据库:

Graphical Representation

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();仅返回空关系。 我会很感激的。

2 个答案:

答案 0 :(得分:0)

根据您的代码,所有内容都是正确的。我想您在数据库中没有正确方式的数据。 添加一些如下所示的数据并检查。

dances

id-1,名称-'Dance A'

id-2,名称-'Dance B'

couples

id-1,名称-'情侣A'

id-2,名称-'情侣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

答案 1 :(得分:0)

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

相关问题