Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel firstOrCreate not working properly?

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'] : '',
]);
like image 645
Stephan-v Avatar asked Dec 11 '22 19:12

Stephan-v


2 Answers

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();
like image 86
schellingerht Avatar answered Dec 20 '22 05:12

schellingerht


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

like image 30
fgilio Avatar answered Dec 20 '22 05:12

fgilio