如何在允许空关系的情况下实现动态关系?

我正在尝试实现的是称为“问题”的表的多态关系

Quesions
-------------
id
title
description
type
metadata_type
metadata_id

Question can be of three types, text-type-question, choice-question, opinion-scale. text-type-question doesn't have any relation table it only requires a basic title and description fields. but the other two requires Extra metadata which is in another two tables whose Model specified in metadata_type

我试图做的是

class SurveyQuestion extends Model
{
    public function metadata()
    {
      return $this->hasOne(app($this->metadata_type));
    }
}

This returns me the metadata fine but my text-type-question doesn't have any relation table, ie $this->metadata_type is null. so it will throw an error.

有没有办法通过检查类型条件来返回空关系?

评论