diff --git a/src/Database/Expression/ValuesExpression.php b/src/Database/Expression/ValuesExpression.php index edb004e21c8..fdaf8e26809 100644 --- a/src/Database/Expression/ValuesExpression.php +++ b/src/Database/Expression/ValuesExpression.php @@ -149,6 +149,9 @@ public function sql(ValueBinder $generator) { foreach ($this->_values as $row) { $row = array_merge($defaults, $row); foreach ($row as $column => $value) { + if ($value instanceof ExpressionInterface) { + $value = $value->sql($generator); + } $type = $this->typeMap()->type($column); $generator->bind($i++, $value, $type); } diff --git a/tests/TestCase/Database/QueryTest.php b/tests/TestCase/Database/QueryTest.php index b6480aa2b24..0a641fb0f94 100644 --- a/tests/TestCase/Database/QueryTest.php +++ b/tests/TestCase/Database/QueryTest.php @@ -2294,6 +2294,27 @@ public function testInsertFailureMixingTypesQueryFirst() { ->values(['name' => 'mark']); } +/** + * Test that insert can use expression objects as values. + * + * @return void + */ + public function testInsertExpressionValues() { + $query = new Query($this->connection); + $query->insert(['title']) + ->into('articles') + ->values(['title' => $query->newExpr("SELECT 'jose'")]); + + $result = $query->sql(); + $this->assertQuotedQuery( + "INSERT INTO \(\) VALUES (?)", + $result, + true + ); + $result = $query->execute(); + $this->assertCount(1, $result); + } + /** * Tests that functions are correctly transformed and their parameters are bound * diff --git a/tests/TestCase/ORM/QueryRegressionTest.php b/tests/TestCase/ORM/QueryRegressionTest.php index d69ca8dc467..2336286067d 100644 --- a/tests/TestCase/ORM/QueryRegressionTest.php +++ b/tests/TestCase/ORM/QueryRegressionTest.php @@ -292,6 +292,19 @@ public function testSaveWithCallbacks() { $this->assertSame($article, $articles->save($article)); } +/** + * Test that save() works with entities containing expressions + * as properties. + * + * @return void + */ + public function testSaveWithExpressionProperty() { + $articles = TableRegistry::get('Articles'); + $article = $articles->newEntity(); + $article->title = new \Cake\Database\Expression\QueryExpression("SELECT 'jose'"); + $this->assertSame($article, $articles->save($article)); + } + /** * Tests that whe saving deep associations for a belongsToMany property, * data is not removed becuase of excesive associations filtering.