Support the ongoing development of Laravel.io →
Database Eloquent Installation
Last updated 2 years ago.
0

instead of doing it like that you can do:

spending = findOrNew($id); // update its attributes spending->save();

http://stackoverflow.com/questions/20309033/find-or-create-with-eloquent

Last updated 9 years ago.
0

ok, I know this, but

the problem with this is a extra query

in case of " findOrNew($id);" in the background will run

  • get model with SELECT fields FROM table WHERE id = 250
  • if exists { populate Model } else { create new empty Model }
  • popluate Model with new data
  • save(): it will be an insert ot update command

i need, i want to avoid the first extra select

  • create new Model and populate
  • update if the key exits or insert if not - for exmaple replace into in mysql:

https://dev.mysql.com/doc/refman/5.0/en/replace.html

Last updated 9 years ago.
0

I think you're worrying way too much about a single query.

If you're really worried about a single query, then you shouldn't be using Eloquent. Every time you eager load, you are running extra queries...

Otherwise, you might want to look at just using DB. Either options below lets you run your own SQL query.

$sql = 'REPLACE into YOUR_TABLE(id, categoryId, etc.) VALUES (1, 2, etc.)';

// Option 1
\DB::connection()->getPdo()->exec( $sql );

// Option 2
\DB::statement( $sql );
Last updated 9 years ago.
0

I agree.. but it also depends on how big/complicated your site is and at what stage is it in terms of users. if there are only 10 or so users using it, i wouldnt worry.. if there are loads.. then i would do a lot more than worry about this..

There is one other solution that comes to my mind, not sure how viable that is.. if you are using database that supports trigger..

you could add a trigger to creating new rows and then check if there is a row matching your input if it is do an update else do a create... ..

0

Sign in to participate in this thread!

Eventy

Your banner here too?

cyrip cyrip Joined 20 Oct 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.