当我尝试使用laravel 5.5.41在数据库中保存对象时出现此错误
这是我的代码
$game = new Game;
$game->name = $itemFetched["name"];
$game->image = $itemFetched["image"];
$game->wikipediaPageUrl = $itemFetched["wikipediaPageUrl"];
$game->wikipediaPageName = $itemFetched["wikipediaPageName"];
$game->wikipediaPageSlug = $itemFetched["wikipediaPageSlug"][0;
$game->save();
$gameid = $game->id;
这是我得到的错误:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list'
(SQL:
insert into `games`
(`0`, `1`, `2`, `3`, `4`, `5`, `name`, `image`, `wikipediaPageUrl`, `wikipediaPageName`, `wikipediaPageSlug`,
`updated_at`, `created_at`) values
(name, image, metadata, wikipediaPageUrl, wikipediaPageName, wikipediaPageSlug,
TestName, https://testimageurlvalue.png,
https://testPageUrlValue.it, testPageNameValue, testPageSlugValue,
2018-08-08 17:08:42,
2018-08-08 17:08:42))
我已经尝试过这样:
$gameToImport = array(
'name' => $itemFetched["name"],
'image' => $itemFetched["image"],
'metadata' => json_encode($itemFetched["metadata"]),
'wikipediaPageUrl' => $itemFetched["wikipediaPageUrl"],
'wikipediaPageID' => $itemFetched["wikipediaPageID"],
'wikipediaPageName' => $itemFetched["wikipediaPageName"],
'wikipediaPageSlug' => $itemFetched["wikipediaPageSlug"]
);
$game = new Game($gameToImport);
$game->save();
然后将save()切换为create(),结果几乎相同,我发现插入记录的唯一方法是使用insert方法,但是我无法获得新记录的ID,甚至$ game-> id为空。.我也尝试将-> id()或-> id附加到插入调用,但没有成功。.
请有人可以帮助我了解问题所在吗?
答案 0 :(得分:0)
如果您尝试:
$game = new Game;
$game->name = $itemFetched["name"];
$game->image = $itemFetched["image"];
$game->wikipediaPageUrl = $itemFetched["wikipediaPageUrl"];
$game->wikipediaPageName = $itemFetched["wikipediaPageName"];
$game->wikipediaPageSlug = $itemFetched["wikipediaPageSlug"];
$game->save();
$gameid = $game->id;
答案 1 :(得分:0)
我强烈建议您使用create方法,但是如果您已经使用insert并工作过,则可以尝试:
$game_id = DB::table('games')->insertGetId($itemFetched);
或
$game_id = DB::table('games')->insertGetId(['name'=>$itemFetched["name"],
'image' => $itemFetched["image"]]);
答案 2 :(得分:0)
我有同样的问题。我意识到我在Eloquent模型类中使用了受保护的$ attributes。我已删除了该受保护的变量,然后此问题得以解决。