Malek Hijazi
Malek Hijazi

Reputation: 4162

How to add an if condition for model relationships

I have an id in a table based on a type.

What I would like to do is return a relationship based on the column value

public function to(){
    if($this->type === 0){
        return $this->hasOne("App\Model\X", "id","created_by");
    }else{
        return $this->hasOne("App\Model\Y", "id","to_id");
    }
}

Upvotes: 2

Views: 505

Answers (1)

user320487
user320487

Reputation:

This is what polymorphic relationships are intended for. The model with the varying column value can morphTo the related type.

Polymorphic relations allow a model to belong to more than one other model on a single association. For example, imagine users of your application can "comment" both posts and videos. Using polymorphic relationships, you can use a single comments table for both of these scenarios.

Upvotes: 2

Related Questions