【问题标题】:Laravel table inheritance. How to create relationshipsLaravel 表继承。如何建立关系
【发布时间】:2019-10-31 23:19:00
【问题描述】:

我有以下代表购买的表格。购买包含许多项。一个项目可以是两种可能的类型 MaterialItem / ServiceItem。 一个 Material Item 有一个 Material 关联,而一个 ServiceItem 只包含几个文本字段。

表“purchases_item_base”包含两种可能的项目类型的共同列。

如何在我的采购模型中定义两种关系,一种用于检索关联的材料项,另一种用于服务项?

    // TABLE 1 purchases
    Schema::create('purchases', function(Blueprint $table) {
        $table->bigIncrements("id")->unsigned();            
        $table->text("details");            
        $table->timestamps();
        $table->softDeletes();
    });



    // TABLE 2 purchases_item_base
    Schema::create('purchases_item_base', function(Blueprint $table) {
        $table->bigIncrements("id")->unsigned();
        $table->unsignedBigInteger("purchase_id")->unsigned();          
        $table->decimal("price", 15 , 2);            
        $table->unsignedTinyInteger("priority");
        $table->text("obs");
        $table->timestamps();
    });

    Schema::table('purchases_item_base', function(Blueprint $table) {
        $table->foreign('purchase_id')->references('id')->on('purchases');            
    });



   // TABLE 3 materials
    Schema::create('materials', function(Blueprint $table) {
        $table->bigIncrements("id")->unsigned();
        $table->string('color');
        $table->string('weight');
        $table->string('brand');
        $table->string('model');
    });



    // TABLE 4 purchase_item_material
    Schema::create('purchase_item_material', function(Blueprint $table) {
        $table->unsignedBigInteger("base_item_id")->unsigned();
        $table->unsignedBigInteger("material_id")->unsigned();
        $table->unsignedInteger("quantity")->default(1);
    });

    Schema::table('purchase_item_material', function(Blueprint $table) {
        $table->foreign('base_item_id')->references('id')->on('purchases_item_base');
        $table->foreign('material_id')->references('id')->on('materials');
    });




    // TABLE 5 purchase_item_service
    Schema::create('purchase_item_service', function(Blueprint $table) {
        $table->unsignedBigInteger("base_item_id")->unsigned();
        $table->string("pn_number");
        $table->text("description");
    });

    Schema::table('purchase_item_service', function(Blueprint $table) {
        $table->foreign('base_item_id')->references('id')->on('purchases_item_base');            
    })

【问题讨论】:

  • 这种情况需要使用hasManyThrough关系。
  • 我不知道怎么做?我认为为此需要多态关系。如您所见,我在两个项目类型表(purchase_item_material、purchase_item_service)中有一个 FK。
  • @FarrukhAyyaz 我不知道如何从中获取中间表中包含的所有数据

标签: laravel laravel-5 eloquent


【解决方案1】:

尝试使用一对多的多态关系

请参阅文档以更好地理解 https://laravel.com/docs/5.8/eloquent-relationships#one-to-many-polymorphic-relations

【讨论】:

    猜你喜欢
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 2017-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多