laravel firstOrCreate 无法正常工作?
laravel firstOrCreate not working properly?
我正在使用 foursquare api 导入一些数据。我的数据库包含多个 foursquare_id 重复项。我这里的代码有问题吗?
我认为这种设置方式将检查数据库中的列值 foursquare_id?
Bar::firstOrCreate([
// do not check for these 2 below because they are mandatory
'foursquare_id' => $item['venue']['id'],
'name' => $item['venue']['name'],
'postalCode' => isset($item['venue']['location']['postalCode']) ? $item['venue']['location']['postalCode'] : '',
'city' => isset($item['venue']['location']['city']) ? $item['venue']['location']['city'] : '',
]);
没错。如果您传递的数组的 所有 元素存在于行对象中,您只会收到 'first'。
备选方案是使用 firstOrNew:
$foo = Bar::firstOrNew(['foursquare_id' => $item['venue']['id']]); // find the object with this foursquare_id. Nothing found? Create a new one with the given foursquare_id
$foo->name = $item['venue']['name'];
$foo->postalCode = isset($item['venue']['location']['postalCode']) ? $item['venue']['location']['postalCode'] : '';
$foo->city = isset($item['venue']['location']['city']) ? $item['venue']['location']['city'] : '';
$foo->save();
此外,firstOrNew
将收到 2 个参数。第一个用于查询,第二个仅用于创建。
所以你可以通过foursquare_id
查询,如果有none就用所有的参数创建。
像这样:
Bar::firstOrCreate(
// Query only by foursquare_id
['foursquare_id' => $item['venue']['id']],
// But, if ends up creating a Bar, also add this parameters
[
'name' => $item['venue']['name'],
'postalCode' => isset($item['venue']['location']['postalCode']) ? $item['venue']['location']['postalCode'] : '',
'city' => isset($item['venue']['location']['city']) ? $item['venue']['location']['city'] : '',
]
);
我正在使用 foursquare api 导入一些数据。我的数据库包含多个 foursquare_id 重复项。我这里的代码有问题吗?
我认为这种设置方式将检查数据库中的列值 foursquare_id?
Bar::firstOrCreate([
// do not check for these 2 below because they are mandatory
'foursquare_id' => $item['venue']['id'],
'name' => $item['venue']['name'],
'postalCode' => isset($item['venue']['location']['postalCode']) ? $item['venue']['location']['postalCode'] : '',
'city' => isset($item['venue']['location']['city']) ? $item['venue']['location']['city'] : '',
]);
没错。如果您传递的数组的 所有 元素存在于行对象中,您只会收到 'first'。
备选方案是使用 firstOrNew:
$foo = Bar::firstOrNew(['foursquare_id' => $item['venue']['id']]); // find the object with this foursquare_id. Nothing found? Create a new one with the given foursquare_id
$foo->name = $item['venue']['name'];
$foo->postalCode = isset($item['venue']['location']['postalCode']) ? $item['venue']['location']['postalCode'] : '';
$foo->city = isset($item['venue']['location']['city']) ? $item['venue']['location']['city'] : '';
$foo->save();
此外,firstOrNew
将收到 2 个参数。第一个用于查询,第二个仅用于创建。
所以你可以通过foursquare_id
查询,如果有none就用所有的参数创建。
像这样:
Bar::firstOrCreate(
// Query only by foursquare_id
['foursquare_id' => $item['venue']['id']],
// But, if ends up creating a Bar, also add this parameters
[
'name' => $item['venue']['name'],
'postalCode' => isset($item['venue']['location']['postalCode']) ? $item['venue']['location']['postalCode'] : '',
'city' => isset($item['venue']['location']['city']) ? $item['venue']['location']['city'] : '',
]
);