From b93acdd9e73195c6220581d8d0254cb24e85c202 Mon Sep 17 00:00:00 2001 From: Mohamed Said Date: Tue, 28 Feb 2017 17:35:44 +0200 Subject: [PATCH] fix SqlServer compilation for delete with JOINs and using table aliases --- .../Database/Query/Grammars/SqlServerGrammar.php | 8 +++++++- tests/Database/DatabaseQueryBuilderTest.php | 5 +++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php b/src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php index df2064a4e536..729814aa5f09 100755 --- a/src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php +++ b/src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php @@ -269,7 +269,13 @@ protected function compileDeleteWithJoins(Builder $query, $table, $where) { $joins = ' '.$this->compileJoins($query, $query->joins); - return trim("delete {$table} from {$table}{$joins} {$where}"); + $alias = $table; + + if (strpos(strtolower($table), ' as ') !== false) { + $alias = explode(' as ', $table)[1]; + } + + return trim("delete {$alias} from {$table}{$joins} {$where}"); } /** diff --git a/tests/Database/DatabaseQueryBuilderTest.php b/tests/Database/DatabaseQueryBuilderTest.php index 1a9fdf9741bc..94662dcee54b 100755 --- a/tests/Database/DatabaseQueryBuilderTest.php +++ b/tests/Database/DatabaseQueryBuilderTest.php @@ -1448,6 +1448,11 @@ public function testDeleteWithJoinMethod() $result = $builder->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->where('email', '=', 'foo')->delete(); $this->assertEquals(1, $result); + $builder = $this->getSqlServerBuilder(); + $builder->getConnection()->shouldReceive('delete')->once()->with('delete [a] from [users] as [a] inner join [users] as [b] on [a].[id] = [b].[user_id] where [email] = ?', ['foo'])->andReturn(1); + $result = $builder->from('users AS a')->join('users AS b', 'a.id', '=', 'b.user_id')->where('email', '=', 'foo')->orderBy('id')->limit(1)->delete(); + $this->assertEquals(1, $result); + $builder = $this->getSqlServerBuilder(); $builder->getConnection()->shouldReceive('delete')->once()->with('delete [users] from [users] inner join [contacts] on [users].[id] = [contacts].[id] where [users].[id] = ?', [1])->andReturn(1); $result = $builder->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->delete(1);