In this case, using a many-to-many relationship might be overkill since the general case is that an invoice will be calculated with only one table price. Instead, you can handle this scenario by introducing a pivot table to store the relationship between invoices and table prices.
Here's how you can set it up:
- Create a new migration to create the pivot table:
php artisan make:migration create_invoice_table_price_table --create=invoice_table_price
- In the generated migration file, define the schema for the pivot table:
public function up()
{
Schema::create('invoice_table_price', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('invoice_id');
$table->unsignedBigInteger('table_price_id');
$table->timestamps();
$table->foreign('invoice_id')->references('id')->on('invoices')->onDelete('cascade');
$table->foreign('table_price_id')->references('id')->on('table_prices')->onDelete('cascade');
});
}
- Run the migration to create the pivot table:
php artisan migrate
- Update your models to define the relationship:
In the Invoice model:
public function tablePrices()
{
return $this->belongsToMany(TablePrice::class);
}
In the TablePrice model:
public function invoices()
{
return $this->belongsToMany(Invoice::class);
}
- When creating an invoice, you can associate one or multiple table prices using the
attachmethod:
$invoice = new Invoice;
$invoice->save();
$invoice->tablePrices()->attach($tablePrice1);
$invoice->tablePrices()->attach($tablePrice2);
- To retrieve the table prices associated with an invoice, you can use the
tablePricesrelationship:
$invoice = Invoice::find($invoiceId);
$tablePrices = $invoice->tablePrices;
By using a pivot table, you can handle the scenario where an invoice may have multiple table prices.