Support the ongoing development of Laravel.io →
posted 9 years ago
Eloquent
Last updated 2 years ago.
0
Solution

How many types do you have? A switch statement might work well.

class Project extends Model {

    public function type()
    {
        switch ($this->$type)
        {
            case 'wordpress':
                return $this->hasOne('App\WordpressProject');
            case 'anotherType':
                return $this->hasOne('App\AnotherTypeOfProject');
        }
    }

}
0

It seems basically the same logic. So it is not a bad way to do it? Making relationships conditional by putting if statement around Eloquent relationship.

Last updated 9 years ago.
0

I couldn't comment if there is logically a better solution. It certainly is not a bad one. I assumed that you wanted a way to express the possibility of having many relationships that's all.

0

Thanks, at least I am more confident now :)

0

There seems to be a new related video on Laracast about this problem although the video does not cover the situation when there are different fields/columns needed depending on the type (e.g. user of type admin may have more data than regular users).

https://laracasts.com/lessons/global-query-scopes

Last updated 9 years ago.
0

Check out the polymorphic relations documentation. This might be what you need.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.