Both solutions are valid and efficient, but the second option with a pivot table would be more flexible in the long run. It allows for easier management of prices and products, as well as the ability to add additional attributes to the pivot table if needed.
Here's an example of how you could set up the tables and relationships in Laravel:
// Product model
class Product extends Model
{
public function prices()
{
return $this->belongsToMany(Price::class)->withPivot('date');
}
}
// Price model
class Price extends Model
{
public function products()
{
return $this->belongsToMany(Product::class)->withPivot('date');
}
}
// Pivot table migration
Schema::create('price_product', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('price_id');
$table->unsignedBigInteger('product_id');
$table->date('date');
$table->timestamps();
$table->foreign('price_id')->references('id')->on('prices')->onDelete('cascade');
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
});
With this setup, you can easily retrieve a product's prices and dates:
$product = Product::find(1);
$prices = $product->prices;
foreach ($prices as $price) {
echo $price->price . ' on ' . $price->pivot->date;
}