【问题标题】:Seed related model with dynamic attribute具有动态属性的种子相关模型
【发布时间】:2016-09-22 01:27:27
【问题描述】:

我正在尝试为用户提供相关图片。每个用户最多可以有 5 张图像。图像表有一个位置字段,它是从 0 到 4 的整数。

这是我的代码:

factory(App\User::class, 50)->create()->each(function($user) {
    $user->images()->saveMany(factory(\App\Image::class, rand(2, 5))->make());
});


$factory->define(Goods\Image::class, function(Faker\Generator $faker) {

    return [
        'id'            => $faker->unique()->uuid,
        'position'      => ????
    ];
});

如何设置位置值,其值将从0-4递增(根据图像编号)。

我也试过了,但是位置一直都是0:

factory(App\User::class, 50)->create()->each(function($user) {
    $position = 0;
    $user->images()->saveMany(factory(\App\Image::class, rand(2, 5))->make([
        'position' => $position++
    ]));
});

【问题讨论】:

    标签: php database laravel eloquent php-7


    【解决方案1】:

    尝试一下:

    $position = 0;
    factory(App\User::class, 50)->create()->each(function($user) {
        $user->images()->saveMany(factory(\App\Image::class, rand(2, 5))->make([
            'position' => $position++
        ]));
    });
    

    【讨论】:

      猜你喜欢
      • 2019-04-25
      • 2011-12-09
      • 1970-01-01
      • 2021-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-03
      相关资源
      最近更新 更多