【问题标题】:create morph relation in Laravel with different foreign key在 Laravel 中使用不同的外键创建变形关系
【发布时间】:2021-07-24 23:51:35
【问题描述】:

我想在 Laravel 中使用 morph 关系来访问另一个模型,并且我不想使用 id 作为外键来连接它们,实际上我想使用选项表上的 uuid 列作为 morph 关系中的外键。 我要使用 morphrTo 的表:(报表表):

        $table->id();
        $table->unsignedBigInteger('exam_id')->nullable();
        $table->foreign('exam_id')->references('id')->on('exams')->cascadeOnDelete();
        $table->string('optionable_uuid');
        $table->string('optionable_type');
        $table->integer('spend_time')->default(0);
        $table->timestamps();

和相关的morhMany表是:(选项表)

        $table->id();
        $table->string('uuid');
        $table->string('title');
        $table->timestamps();

我的模型如下 // 报表模型

// OptionModelpublic function optionable()
{
    return $this->morphTo();
}

// 选项模型

public function report()
{
    return $this->morphMany(ExamReport::class,'optionable','optionable_type','optionable_uuid','uuid');
}

但是变形关系中的输出数据返回空女巫部分是错误的,我该如何解决?

【问题讨论】:

    标签: php mysql laravel


    【解决方案1】:

    我必须更改 morhTo 模型,如下所示

    public function optionable()
    {
        return $this->morphTo('optionable','optionable_type','optionable_uuid','uuid');
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-04
      • 2020-10-20
      • 2014-11-18
      • 2016-12-07
      • 1970-01-01
      • 2017-08-29
      • 2019-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多