nahoj
nahoj

Reputation: 285

Laravel Seed with Relationship (Real Data)

I'm trying to seed my table with some data with a belongsTo relationship, but I don't know how I should handle this relationship. Can anybody tell me what a belongsTo relationship should look like with seeding real data?

Seed file

public function run()
{
    CarSchema::create([
        'type_of_car' => 'small',
        'horse_power' => 98,
        'brand'       => 3 // Want to get the brand of id 3 here
    ])
 }

The result I want is that "brand" is what corresponds to id 3 in the brand table so in the front End I've got the brand as well and not just the id of it.

Upvotes: 1

Views: 918

Answers (1)

emotality
emotality

Reputation: 13035

Your Car model:

public function brand()
{
    return $this->belongsTo(\App\Brand::class, 'brand_id');
}

Your Brand model:

public function cars()
{
    return $this->hasMany(\App\Car::class);
}

Your cars migration:

public function up()
{
    Schema::create('cars', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->enum('type_of_car', ['small', 'medium', 'large']); // just extra example
        $table->year('year');
        $table->mediumInteger('horse_power');

        // car's brand id below
        $table->unsignedInteger('brand_id');
        $table->foreign('brand_id')->references('id')->on('brands')->onDelete('cascade');
    });
}

To seed your cars table, you can insert any id from brands table into brand_id in your cars table, for example:

Car::create([
    'name'        => 'S4',
    'type_of_car' => 'medium',
    'year'        => '2014',
    'horse_power' => 333,
    'brand_id'    => 3 // <-- this id should exist in brands table
]);

If you are seeding cars with random brands, you can insert a random brand id instead of hardcoding the id (like I did above with brand_id being 3):

...
    'brand_id' => \App\Brand::all('id')->random()->id
]);

Upvotes: 1

Related Questions