AndrewMcLagan
AndrewMcLagan

Reputation: 13987

Multiple unique morphMany relations Laravel 4

In Laravel 4 Eloquent is it possible to have a model that has two or more unique morphMany() relations to another model? (polymorphic)

e.g.

class Application extends Eloquent {

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

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

...

The code above does not work as when i try to retrieve either of the relations sometime get an upload model that i dont want e.g.

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

Upvotes: 2

Views: 1759

Answers (1)

Lance Pioch
Lance Pioch

Reputation: 1167

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!

Upvotes: 1

Related Questions