Ste*_*n-v 2 php unique laravel eloquent laravel-5.1
我用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'] : '',
]);
Run Code Online (Sandbox Code Playgroud)
sch*_*rht 10
那就对了.如果传递的数组的所有元素都存在于行对象中,则只会收到"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();
Run Code Online (Sandbox Code Playgroud)