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 support for inserting multiple rows using a subquery #7538

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/Framework/QueryBuilder/Concerns/CRUD.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Give\Framework\QueryBuilder\Concerns;

use Give\Framework\Database\DB;
use Give\Framework\QueryBuilder\QueryBuilder;

/**
* @since 2.19.0
Expand All @@ -29,6 +30,26 @@ public function insert($data, $format = null)
);
}

/**
* @unreleased
*
* @param string $table
* @param array $columns
*
* @return false|int
*/
public function insertInto(string $table, array $columns)
{
return DB::query(
sprintf(
'INSERT INTO %s (%s) %s',
$this->prefixTable($table),
implode(', ', $columns),
$this->getSQL()
)
);
}

/**
* @see https://developer.wordpress.org/reference/classes/wpdb/update/
*
Expand Down
21 changes: 21 additions & 0 deletions tests/Unit/Framework/QueryBuilder/CRUDTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,27 @@ public function testInsertShouldAddRowToDatabase()
$this->assertEquals($data['post_content'], $post->post_content);
}

/**
* @unreleased
*/
public function testInsertIntoShouldAddSubQueryAsMultipleRowsToTheDatabase()
{
DB::table('posts')->insert(['post_title' => 'Aye Post']);
$postIdAye = DB::last_insert_id();

DB::table('posts')->insert(['post_title' => 'Bee Post']);
$postIdBee = DB::last_insert_id();

DB::table('posts')
->select(['ID', 'post_id'])
->selectRaw('(SELECT "postTitle") as meta_key')
->select(['post_title', 'meta_value'])
->insertInto('postmeta', ['post_id', 'meta_key', 'meta_value']);

$this->assertEquals('Aye Post', get_post_meta($postIdAye, 'postTitle', true));
$this->assertEquals('Bee Post', get_post_meta($postIdBee, 'postTitle', true));
}

/**
* @since 2.19.0
*
Expand Down
Loading