我试图通过Faker,NeoEloquent和Eloquent的Seeder类来播种neo4j数据库(第一次)。它使一家零售商,两家公司,一些产品和一起产品有关。
Retailer -> Many-Many -> Product
Retailer -> One-Many -> Company
Company -> One-Many -> Product
public function run()
{
Eloquent::unguard();
$faker = Faker\Factory::create();
// Retailer
Retailer::createWith([
[
'name' => $faker->company
],
[
'companies' =>
[
[
'company_id' => $faker->randomNumber(8),
'name' => $faker->company, 'active' => 1
],
[
'company_id' => $faker->randomNumber(8),
'name' => $faker->company, 'active' => 1
]
]
]
]);
// Products
for ($i = 1; $i < 3; $i++)
{
for ($j = 1; $j < $faker->numberBetween(1,3); $j++)
{
$product = Product::create([
'product_id' => $faker->randomNumber(8),
'name' => $faker->name,
'active' => '1',
'time_added' => $faker->date,
'price' => $faker->numberBetween(1,999),
]);
$retailer = Retailer::find(1);
$retailer->products()->save($product); // error here
$company = Company::find($i);
$company->products()->save($product);
}
}
}
{"error":
{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException",
"message":"Call to undefined method Illuminate\\Database\\Eloquent\\Collection::products()",
"file":"D:\\Swaggable\\Laravel\\app\\database\\seeds\\DatabaseSeeder.php",
"line":62}}
我无法想办法解决这个问题......
答案 0 :(得分:1)
我认为不是:
$retailer->products()->save($product);
你应该使用:
$retailer->products->save($product);
之后:
$retailer = Retailer::find(1);
如果零售商不为空,您应该添加额外的检查,例如:
if (is_null($retailer)) {
die('retailer not found')
}
如果你不知道零售商的ID是什么,你应该使用:
$retailer = Retailer::orderby('id', 'desc')->first();
查找此数组中的最后一条记录