Intermediate tables and pivot relationships

0

I have the following 3 tables with the relationships shown in the image

In the models of Laravel I am defining the relations with the intermediate table in the following way:

Table model discounts ;

class Discount extends Model
{
    protected $table = 'discounts';

    public function discount_products(){
        $this->belongsToMany('App\Models\Product', 'product_has_discount', 'product_id', 'id');
    }
}

Table model products

class Product extends Model
{
    protected $table = 'products';

    public function product_discounts(){
        $this->belongsToMany('App\Models\Discount', 'product_has_discount', 'discount_id', 'id');
    }

}

In the migrations of my tables I already have the foreign keys assigned correctly.

I want to know if the N: N relationship of the tables is correct, if the relationships I am doing in Laravel are also good and how I would add records from one side or the other to save in the intermediate table, thank you.

    
asked by Ray 07.07.2018 в 20:43
source

1 answer

0

You must make a correction on your models.

Model of the discounts table:

class Discount extends Model
{
    protected $table = 'discounts';

    public function discount_products(){
        $this->belongsToMany('App\Models\Product', 'product_has_discount', 'product_id', 'dicount_id');
    }
}

Model of the products table:

class Product extends Model
{
    protected $table = 'products';

    public function product_discounts(){
        $this->belongsToMany('App\Models\Discount', 'product_has_discount', 'discount_id', 'product_id');
    }

}

You can take what the documentation says as a reference: Many To Many

    
answered by 09.07.2018 в 06:07