jeudi 31 octobre 2019

Laravel table inheritance. How to create relationships

I have the following tables that represent a Purchase. A Purchase contains many items. An item can be of two possible types MaterialItem / ServiceItem. A Material Item has a Material associated while a ServiceItem only contains a few text fields.

Table "purchases_item_base" contains the columns in common of the two possible item types.

How can I define two relationships in my Purchase model, one for retrieving the associated Material Items and another for the Service items?

    // 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');            
    })


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire