Laravel播种机不工作

时间:2016-06-13 20:50:39

标签: php laravel seeding

有人能看到我的播种机出现的问题吗?

public function run()
{
    $faker = Faker\Factory::create();
    $limit = 30;

    $userId = App\User::all()->lists('id')->toArray();
    $status = App\OrderStatus::all()->lists('id')->toArray();


    for ($i = 0; $i < $limit; $i++) {
        $chosenUserId = $faker->randomElement($userId);
        $user = App\User::find($chosenUserId);

        DB::table('orders')->insert([
            'created_at' => $faker->date('Y-m-d'),
            'user_id'    => $chosenUserId,
            'status_id'  => $faker->randomElement($status),
            'draft'      => false,
            'address_id' => $user->addresses->first()->id
        ]);
    }
}

我一直收到trying to get property of non-object错误,我想这是因为我附加address_id的最后一行。

当我查看数据库之前创建的内容时,用户和地址创建正常,每个用户都分配了一个地址。

在用户模型中,我有:

public function addresses()
{
    return $this->hasMany('App\Address');
}

2 个答案:

答案 0 :(得分:0)

下面:

addresses -> addresses()

答案 1 :(得分:0)

由于您的用户模型具有定义与地址模型的关系的功能,因此您应该将其称为函数而不是对象属性:

    DB::table('orders')->insert([
        'created_at' => $faker->date('Y-m-d'),
        'user_id'    => $chosenUserId,
        'status_id'  => $faker->randomElement($status),
        'draft'      => false,
        'address_id' => $user->addresses()->first()->id
    ]);