-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNativeSQLMapperTrait.php
More file actions
63 lines (58 loc) · 2.13 KB
/
NativeSQLMapperTrait.php
File metadata and controls
63 lines (58 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<?php
declare(strict_types=1);
namespace Bancer\NativeQueryMapper\ORM;
use Cake\Database\StatementInterface;
/**
* NativeSQLMapperTrait
*
* Provides convenience functions for working with native SQL queries in
* CakePHP Table classes. It allows preparing raw SQL statements using
* the table's connection driver and wrapping executed statements in a
* NativeQueryResultMapper object, enabling automatic entity and association
* mapping based on CakePHP-style column aliases.
*/
trait NativeSQLMapperTrait
{
/**
* Wrap a prepared statement in a NativeQueryResultMapper, enabling the
* mapping of native SQL result sets into fully hydrated entities.
*
* Typically used after calling prepareNativeStatement() and binding
* the statement parameters.
*
* Example:
* ```php
* $stmt = $ArticlesTable->prepareNativeStatement("
* SELECT id AS Articles__id FROM articles
* ");
* $entities = $ArticlesTable->mapNativeStatement($stmt)->all();
* ```
*
* @param \Cake\Database\StatementInterface $stmt Prepared statement.
* @return \Bancer\NativeQueryMapper\ORM\NativeQueryResultMapper Wrapper for ORM-level mapping of native results.
*/
public function mapNativeStatement(StatementInterface $stmt): NativeQueryResultMapper
{
return new NativeQueryResultMapper($this, $stmt);
}
/**
* Prepare a native SQL statement using the table's database
* connection driver. This provides direct access to low-level PDO-style
* prepared statements while still using the CakePHP connection.
*
* Example:
* ```php
* $stmt = $ArticlesTable->prepareNativeStatement("
* SELECT id AS Articles__id FROM articles WHERE title = :title
* ");
* $stmt->bindValue('title', 'Example');
* ```
*
* @param string $stmt Raw SQL string to prepare.
* @return \Cake\Database\StatementInterface Prepared statement ready for parameter binding and execution.
*/
public function prepareNativeStatement(string $stmt): StatementInterface
{
return $this->getConnection()->getDriver()->prepare($stmt);
}
}