Skip to content
This repository was archived by the owner on May 12, 2022. It is now read-only.

Commit 2cda2e4

Browse files
author
Nik Barham
committed
Adding "INSERT IGNORE" into Query Builder.
Fixing bug where M-M joins which get pushed duplicate items cause SQL Contraint errors
1 parent 4d550ab commit 2cda2e4

File tree

3 files changed

+21
-3
lines changed

3 files changed

+21
-3
lines changed

src/Automatorm/Database/QueryBuilder.php

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,9 +100,9 @@ public static function count($table, $column = '*')
100100
* @param mixed[] $columndata List of column => data to insert
101101
* @return Automatorm\Database\QueryBuilder
102102
*/
103-
public static function insert($table, array $columndata = [])
103+
public static function insert($table, array $columndata = [], $insert_ignore = false)
104104
{
105-
$query = new static('insert');
105+
$query = $insert_ignore ? new static ('insertignore') : new static('insert');
106106
$query->set = $columndata;
107107
if ($table instanceof QueryBuilder) {
108108
$query->table_subquery = $table->resolve();
@@ -462,6 +462,13 @@ public function resolve()
462462

463463
return ["INSERT INTO $table{$join}{$data}{$limit}", $this->data];
464464

465+
case 'insertignore':
466+
$join = $this->resolveJoins();
467+
$data = $this->resolveColumnData();
468+
$limit = $this->resolveLimit();
469+
470+
return ["INSERT IGNORE INTO $table{$join}{$data}{$limit}", $this->data];
471+
465472
case 'update':
466473
$join = $this->resolveJoins();
467474
$data = $this->resolveColumnData();

src/Automatorm/Orm/Data.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -684,7 +684,7 @@ protected function buildQuery(&$query)
684684
$pivot['id'] => $origin_id, // Id of this object
685685
$pivot['connections'][0]['column'] => $object->id // Id of object linked to this object
686686
];
687-
$query->sql(QueryBuilder::insert($table, $newdata));
687+
$query->sql(QueryBuilder::insert($table, $newdata, true));
688688
}
689689
}
690690
}

test/Database/QueryBuilderTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,17 @@ public function testSimpleInsert()
3535
$this->assertEquals('foo', $data[1]);
3636
}
3737

38+
public function testSimpleInsertIgnore()
39+
{
40+
$qb = QueryBuilder::insert('test', ['id' => 1, 'value' => 'foo'], true);
41+
list($sql, $data) = $qb->resolve();
42+
43+
$this->assertEquals('INSERT IGNORE INTO `test` SET `id` = ?, `value` = ?', $sql);
44+
$this->assertEquals(2, count($data));
45+
$this->assertEquals(1, $data[0]);
46+
$this->assertEquals('foo', $data[1]);
47+
}
48+
3849
public function testSimpleUpdate()
3950
{
4051
$qb = QueryBuilder::update('test', ['id' => 1, 'value' => 'foo']);

0 commit comments

Comments
 (0)