5

I am importing some data with the foursquare api. My database contains multiple foursquare_id duplicates. Am I doing something wrong with the code here?

I thought the way this is set up it will check the database for the column value of 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'] : '',
]);
Stephan-v
  • 19,255
  • 31
  • 115
  • 201

2 Answers2

11

That's right. You only receive the 'first' if all elements of your passed array exist in the row object.

The alternative is using 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();
schellingerht
  • 5,726
  • 2
  • 28
  • 56
2

Also, firstOrNew will receive 2 arguments. The first is for querying, the second only for creating.

So you can query by foursquare_id, and if there's none create with all the parameters.

Like this:

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'] : '',
    ]
);

More in the docs: https://laravel.com/docs/5.5/eloquent

fgilio
  • 103
  • 4
  • 11