Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Add an insertInto method to the Query Builder #2

Open
JasonTheAdams opened this issue Sep 28, 2022 · 1 comment
Open

Feature: Add an insertInto method to the Query Builder #2

JasonTheAdams opened this issue Sep 28, 2022 · 1 comment
Labels
enhancement New feature or request

Comments

@JasonTheAdams
Copy link

SQL provides the ability to Insert Into a table using the results of another query. This is incredibly useful, especially as a means of migration or conditionally inserting rows.

Take the following example:

global $wpdb;

$donationMetaTable = "{$wpdb->prefix}give_donationmeta";
$subscriptionTable = "{$wpdb->prefix}give_subscriptions";

$wpdb->query(
    "
        INSERT INTO $donationMetaTable (donation_id, meta_key, meta_value)
        SELECT
            p.ID,
            'subscription_id',
            s.id
        FROM
            $wpdb->posts AS p
            LEFT JOIN $donationMetaTable AS dm1 ON dm1.donation_id = p.ID
                AND dm1.meta_key = 'subscription_id'
            LEFT JOIN $donationMetaTable AS dm2 ON dm2.donation_id = p.ID
                AND dm2.meta_key = '_give_subscription_payment'
            LEFT JOIN $subscriptionTable AS s ON s.parent_payment_id = p.ID
        WHERE
            dm2.meta_value = '1'
            AND dm1.meta_value IS NULL
    "
);

This inserts subscription_id meta into the donation meta table, but only for cases where it's missing. So if this query were to run twice the second time it runs it would do nothing! ✨

It would be awesome to have something like the following:

DB::table('donationmeta')
  ->insertInto(
    DB::table('posts')->select()->where(); // set up query
  );
@kjohnson
Copy link

Discussion Summary

We discussed inverting the relationship between the INSERT INTO query and the related sub-query.

Leveraging the Query Builder we can define the SELECT as the main logic of the query which can then be inserted into another table, which more closely matches the application logic.

DB::table('posts')

    // Subquery
    ->select(['ID', 'post_id'])
    ->selectRaw('(SELECT "postTitle") as meta_key')
    ->select(['post_title', 'meta_value'])

    // Insert Into
    ->insertInto('postmeta', ['post_id', 'meta_key', 'meta_value']);
INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
    SELECT
        ID AS post_id,
        (SELECT "postTitle") as meta_key,
        post_title AS meta_value
    FROM wp_posts;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants