2

在 Laravel 4 Eloquent 中,是否有可能有一个模型与另一个模型有两个或多个独特的 morphMany() 关系?(多态)

例如

class Application extends Eloquent {

    public function resume()
    {
        return $this->morphMany('Upload', 'uploadable');
    }    

    public function coverLetter()
    {
        return $this->morphMany('Upload', 'uploadable');
    }  

...

上面的代码不起作用,因为当我尝试检索任何一个关系时,有时会得到一个我不想要的上传模型,例如

$application->resume->file_name // this sometimes echos a coverLetter
4

1 回答 1

1

It looks like you're misunderstanding why polymorphic relations should be used.

This would be your fix:

class Application extends Eloquent {

public function resume()
{
    return $this->hasMany('Resume');
}    

public function coverLetter()
{
    return $this->hasMany('CoverLetter');
}  

// ...

The reason that you can't have both as polymorphic is because you simply can't tell which one you should be getting. Your 'uploadable' could be a coverletter or a resume, but you can't tell if they're both being described as uploadable. You have to differentiate them in the models. Laravel isn't that magical!

于 2013-11-08T15:09:17.963 回答