John Davidson

php - How can I generate a unique foreign key while seeding, using Laravel 7?

0 comments
Message:


I've got these two tables linked with a one to one relation. How should the seeders be if I want unique foreign keys in sponsored apartments table?


Model table Apartments:


public function sponsoredapartment() {

return $this -> hasOne(SponsoredApartment::class);
}

Model table Sponsored Apartments


public function apartment() {

return $this -> belongsTo(Apartment::class);
}

Migrations Apartments


Schema::create('apartments', function (Blueprint $table) {
$table->id();

$table -> string('title')->required();
$table -> string('rooms')->required();
$table -> integer('bed');
$table -> integer('bathroom');
$table -> integer('area');
$table -> string('address');
$table -> string('url_img');
$table -> string('features');

$table -> bigInteger('landlord_id')->index()->unsigned();

$table->timestamps();
});

Migrations Sponsored Apartments


    Schema::create('sponsored_apartments', function (Blueprint $table) {

$table -> id();

$table -> date('expired_date');
$table -> bigInteger('apartment_id') -> unsigned() -> index();
$table -> bigInteger('sponsor_id') -> unsigned() -> index();

$table -> timestamps();
});


My Answer:
To generate unique foreign keys while seeding in Laravel 7, you can use the Faker library to generate random data for your seeders. Here's an example of how you can generate unique foreign keys for the sponsored apartments table:

php
use Illuminate\Database\Seeder;
use App\Apartment;
use App\SponsoredApartment;

class DatabaseSeeder extends Seeder
{
public function run()
{
// Seed apartments
factory(Apartment::class, 10)->create()->each(function ($apartment) {
// Seed sponsored apartments with unique foreign keys
$apartment->sponsoredapartment()->save(factory(SponsoredApartment::class)->make([
'apartment_id' => $apartment->id,
'sponsor_id' => rand(1, 10) // Generate a random sponsor_id
]));
});
}
}


In this example, we are using the `factory` method to create 10 apartments and then for each apartment, we are creating a sponsored apartment with a unique foreign key for the `apartment_id` and a random `sponsor_id`.

Make sure to define the factories for both the Apartment and SponsoredApartment models to generate the required data for seeding. You can define the factories in the `database/factories` directory.

After defining the factories, you can run the seeder using the `php artisan db:seed` command to populate your database with the seeded data.

Rate this post

5 of 5 based on 2209 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us