【问题标题】:Laravel Polymorphic relationship model name is stored instead of typeLaravel 存储多态关系模型名称而不是类型
【发布时间】:2021-05-23 21:40:46
【问题描述】:

我使用多态的一对一关系来让多种类型的产品共享一些字段,以优化数据库结构。我有一个 Product 父模型和一个 Shoe 模型。

问题是每次我存储一个产品(鞋子和产品)并且关系发生(productable_id 存储正确)时,在productable_type而不是看到App\Models\Shoe我看到App\Models\Product和我不知道它来自哪里。

以下是关系的方法:

在 Product.php 中

public function productable() {
    return $this->morphTo();
}

在 Shoe.php 中

public function product() {
    return $this->morphOne('App\Models\Product', 'productable');
}

产品表迁移:

$table->id();
$table->foreignId('product_model_id')->constrained('product_models');
$table->foreignId('owner_id')->nullable()->constrained('users')->onUpdate('cascade'); // fields for the model and the product's owner
$table->integer('productable_id');
$table->string('productable_type');

【问题讨论】:

    标签: laravel eloquent polymorphism laravel-8


    【解决方案1】:

    首先,创建 Shoe -

    $shoe = new Shoe();
    // after assign value
    $shoe->save();
    
    // then create Product
    $shoe->product()->create($yourProductData);
    

    【讨论】:

    • 好的,我在那里传递了一个数组,它终于可以工作了!你有关于如何用 Backpack 实现它的想法吗?
    猜你喜欢
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    • 2019-08-15
    • 2016-05-21
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 2017-07-07
    相关资源
    最近更新 更多