-
Notifications
You must be signed in to change notification settings - Fork 0
Adding the first models
Clio Brichaut edited this page Jan 14, 2023
·
1 revision
To create the first two models, Products and Baskets:
-
Run
./vendor/bin/sail artisan make:model Product --alland./vendor/bin/sail artisan make:model Basket --allto generate the models, factories, etc. -
Configure the Product properties (= name, price) by editing
/app/database/migrations/xxxx_xx_xx_xxxxxx_create_products_table.php:
public function up()
{
Schema::create('products', function (Blueprint $table)
{
$table->id();
$table->string('name');
$table->float('price');
$table->timestamps();
});
}- Create the intermediate table with
./vendor/bin/sail artisan make:migration create_basket_product_tableand configure the foreign keys in the generated migration/app/database/migrations/xxxx_xx_xx_xxxxxx_create_basket_product_table.php:
public function up()
{
Schema::create('basket_product', function (Blueprint $table)
{
$table->foreignId('basket_id')->constrained();
$table->foreignId('product_id')->constrained();
$table->dateTime('removal_date')->nullable();
$table->timestamps();
});
}
public function down()
{
Schema::table('basket_product', function (Blueprint $table)
{
$table->dropForeign(['basket_id']);
$table->dropForeign(['product_id']);
});
Schema::dropIfExists('basket_product');
}- Set the ManyToMany relationship in the Models
/app/app/Models/Product.phpand/app/app/Models/Basket.php:
// class Product
/**
* @return BelongsToMany<Basket>
*/
public function baskets(): BelongsToMany
{
return $this->belongsToMany(Basket::class)->withTimestamps()->withPivot('removal_date');
}
// class Basket
/**
* @return BelongsToMany<Product>
*/
public function products(): BelongsToMany
{
return $this->belongsToMany(Product::class)->withTimestamps()->withPivot('removal_date');
}-
Execute the migrations with
./vendor/bin/sail artisan migrate. -
Open http://localhost:8080 to see the database with all its tables (including Laravel's default users, migrations, etc.).