Laravel 4 调用未定义的方法 create()


Laravel 4 Call to undefined method create()

我正在尝试对我的新数据库表进行数据库种子。

产品播种机.php

class ProductSeeder extends DatabaseSeeder {
public function run()
{
    $products = array(
        array(
            'name' => 'DSLR D300S (body only)',
            'image' => 'D300S_16_85_front34l_i.jpg',
            'stock' => 'Available',
            'price'=>'5188.00'
            )
        );

    foreach ($products as $product) {
        Product::create($product);
    }
}
}

型号/产品.php

class Product extends Eloquent{
}

但是,当我运行db:seed时,它说"调用未定义的方法 Product::create()"。

我该如何解决?谢谢。

当依赖模型的数据库种子设定种子不是一个特别好的主意时,当您尝试通过存储库对模型进行单元测试(数据库测试)时,这一点就显得尤为重要。

请改用原始查询构建器(带有流畅的接口)。

DB::table('products')->insert(array(...));

在Laravel中播种的最佳实践是使用'DB::table()':

class ProductSeeder extends DatabaseSeeder {
    public function run()
    {
        $products = array(
                            array(
                                'name' => 'DSLR D300S (body only)',
                                'image' => 'D300S_16_85_front34l_i.jpg',
                                'stock' => 'Available',
                                'price'=>'5188.00'
                                )
                        );
        foreach ($products as $product) {
            DB::table('products')->insert($products);
        }
    }
}

不能说是否是您的问题,但由于播种机文件中的拼写错误,我收到此错误

而不是

Product::create($product);

我有

// note only one semicolon
Product:create($product);

无论如何,这肯定会导致相同的错误!

PHP Fatal error:  Call to undefined function create() 

所以我肯定会建议您再次检查您的代码

此外,我只是扩展播种机而不是数据库播种器所以也试试

class ProductSeeder extends Seeder {

类产品需要有一个方法创建。

class Product extends Eloquent{
    public function create($product)
    {
        // Do something
    }
}