Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

makapaka's avatar

How to do conditional relationship

I am using the same API for different database models and therefore some relationships will depend on which DB we are connected to.

So for example I simply need to be able to do something like

public function players()
{ 
    if (config(isNfl) ) {
        return $this->hasMany(Players::class);
    }
}

public function students()
{
    if (config(isSchool) ) {
        return $this->hasMany(Students::class);
    }
}

I hope that makes some sense - obviously i've mega abbreviated for simplicity. But is something like this possible ? I'm not saying this architecture is the best, but if anyone can advise on accomplishing - i mean, will this work as I expect, that would be great.

Thanks - if possible, any solution should be compatible with v5.2 at least

0 likes
4 replies
bobbybouwmann's avatar

Well you say that it depends on the database connection, but in general your application shouldn't be aware of what kind of tabels there are or not. Your relationships should either return data or an empty collection. If the table exists and there is no data it will always return an empty collection.

Your relationship methods always need to return a relationship type. Your current approach doesn't return anything if the config is not set correctly. This will break your code in the future at some point.

You can work around this by using a query scope as an option, but it's still not the nicest option. In general to make this nicer I would probably create repositories for each domain (so nfl and school). It's up to the repository to use the correct relations than. You don't have to think about this again in your controllers.

May I ask why you want these relationships to be optional?

1 like
makapaka's avatar

@BOBBYBOUWMANN - thanks for the reply.

Its a bit overly complex and to be honest difficult to explain here.

I will look into repositories though - that sounds like a good start, thanks

Please or to participate in this conversation.