如何为模型关系添加 if 条件

How to add an if condition for model relationships

我在 table 中有一个基于类型的 ID。

我想做的是return一个基于列值的关系

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");
    }
}

这就是 polymorphic relationships 的目的。具有不同列值的模型可以 morphTo 相关类型。

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.