Query lang.bind
Testing Is Documentation
Uses
php
<?php
use Leevel\Database\Condition;
use Leevel\Kernel\Utils\Api;
use Tests\Database\DatabaseTestCase as TestCase;
命名参数绑定
php
public function testBaseUse(): void
{
$connect = $this->createDatabaseConnectMock();
$sql = <<<'eot'
[
"SELECT `test_query`.* FROM `test_query` WHERE `test_query`.`id` = :id",
{
"id": [
1
]
},
false
]
eot;
self::assertSame(
$sql,
$this->varJsonSql(
$connect
->table('test_query')
->bind('id', 1)
->where('id', '=', Condition::raw(':id'))
->findAll(),
$connect
)
);
}
命名参数绑定,支持绑定类型
php
public function testBindWithType(): void
{
$connect = $this->createDatabaseConnectMock();
$sql = <<<'eot'
[
"SELECT `test_query`.* FROM `test_query` WHERE `test_query`.`id` = :id",
{
"id": [
1,
"PDO::PARAM_INT"
]
},
false
]
eot;
self::assertSame(
$sql,
$this->varJsonSql(
$connect
->table('test_query')
->bind('id', 1, \PDO::PARAM_INT)
->where('id', '=', Condition::raw(':id'))
->findAll(),
$connect,
1
)
);
}
命名参数绑定,绑定值支持类型定义
php
public function testWithTypeAndValueCanBeArray(): void
{
$connect = $this->createDatabaseConnectMock();
$sql = <<<'eot'
[
"SELECT `test_query`.* FROM `test_query` WHERE `test_query`.`id` = :id",
{
"id": [
1,
"PDO::PARAM_INT"
]
},
false
]
eot;
self::assertSame(
$sql,
$this->varJsonSql(
$connect
->table('test_query')
->bind('id', [1, \PDO::PARAM_INT])
->where('id', '=', Condition::raw(':id'))
->findAll(),
$connect,
2
)
);
}
命名参数绑定,支持多个字段绑定
php
public function testNameBind(): void
{
$connect = $this->createDatabaseConnectMock();
$sql = <<<'eot'
[
"SELECT `test_query`.* FROM `test_query` WHERE `test_query`.`id` = :id AND `test_query`.`hello` LIKE :name",
{
"id": [
1,
"PDO::PARAM_INT"
],
"name": [
"小鸭子"
]
},
false
]
eot;
self::assertSame(
$sql,
$this->varJsonSql(
$connect
->table('test_query')
->bind(['id' => [1, \PDO::PARAM_INT], 'name' => '小鸭子'])
->where('id', '=', Condition::raw(':id'))
->where('hello', 'like', Condition::raw(':name'))
->findAll(),
$connect,
3
)
);
}
问号 ?
参数绑定,支持多个字段绑定
php
public function testQuestionMarkBind(): void
{
$connect = $this->createDatabaseConnectMock();
$sql = <<<'eot'
[
"SELECT `test_query`.* FROM `test_query` WHERE `test_query`.`id` = ? AND `test_query`.`hello` LIKE ?",
[
[
5,
"PDO::PARAM_INT"
],
[
"小鸭子"
]
],
false
]
eot;
self::assertSame(
$sql,
$this->varJsonSql(
$connect
->table('test_query')
->bind([[5, \PDO::PARAM_INT], '小鸭子'])
->where('id', '=', Condition::raw('?'))
->where('hello', 'like', Condition::raw('?'))
->findAll(),
$connect,
4
)
);
}