0

the laravel framework has a handy function that is called updateOrCreate().

How can I do something like this in wordpress, whereas Flight is the model in laravel and could be replaced by $wpdb:

$flight = Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99, 'discounted' => 1]
);

Does something like this also exists for $wpdb?

I appreciate your replies!

1
  • 1
    It might be difficult to answer this correctly without an example of when you might want it in WordPress, it isn't clear what the WP equivalent of a Laravel model is that you have in mind. Generally though, using raw SQL is a code smell and indicates a wrong turn has been taken. wpdb methods are a close second. This usually implies a developer who is unaware of custom post types, meta, and taxonomies Have you checked the WPDB documentation? – Tom J Nowell Apr 24 at 18:52
1

If I'm not too badly mistaken, I don't think there's a similar method in $wpdb. replace, https://developer.wordpress.org/reference/classes/wpdb/#replace-row, is kind of like that, but not quite as sophisticated I believe.

You probably need to build a helper function for that yourself, which wraps update, insert and a bit of logic together. Or use query method with custom sql string as suggested here, WPDB Insert or if exists Update.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.