Laravel Seed with Relationship(Real Data)

时间:2019-01-26 15:15:20

标签: laravel laravel-5 eloquent laravel-seeding

我正在尝试为表中的一些数据使用belongsTo关系,但是我不知道该如何处理这种关系。有人能告诉我播种真实数据时应具有的belongsTo关系如何吗?

种子文件

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

我想要的结果是“品牌”是品牌表中ID 3的对应值,因此在前端,我也拥有品牌,而不仅仅是ID。

1 个答案:

答案 0 :(得分:1)

您的汽车型号:

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
]);

如果您要播种具有随机品牌的汽车,则可以插入随机品牌ID而不是对ID进行硬编码(就像我在上面brand_id为3时所做的那样):

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