Модель вашего автомобиля:
public function brand()
{
return $this->belongsTo(\App\Brand::class, 'brand_id');
}
Модель вашего бренда:
public function cars()
{
return $this->hasMany(\App\Car::class);
}
Ваша cars
миграция:
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');
});
}
Чтобы заполнить таблицу cars
, вы можете вставить любую таблицу id
из таблицы brands
в brand_id
таблицы cars
, например:
Car::create([
'name' => 'S4',
'type_of_car' => 'medium',
'year' => '2014',
'horse_power' => 333,
'brand_id' => 3 // <-- this id should exist in brands table
]);
Если вы сеете автомобили со случайными брендами, вы можете вставить случайный идентификатор бренда вместо жесткого кодирования идентификатора (как я делал выше, когда brand_id равен 3):
...
'brand_id' => \App\Brand::all('id')->random()->id
]);