CakePHP
  • 文档
    • 手册
    • API
    • 视频
    • 报告安全问题
    • 隐私政策
    • 标识和商标
  • 商业解决方案
  • 周边商品
  • 公路旅行
  • 团队
  • 社区
    • 社区
    • 参与进来
    • 问题 (Github)
    • 烘焙坊
    • 精选资源
    • 培训
    • 聚会
    • 我的 CakePHP
    • CakeFest
    • 时事通讯
    • 领英
    • YouTube
    • 脸书
    • 推特
    • Mastodon
    • 帮助和支持
    • 论坛
    • Stack Overflow
    • IRC
    • Slack
    • 付费支持
CakePHP

C CakePHP 5.1 Chiffon API

  • 项目
    • CakePHP
      • CakePHP
      • Chronos
      • Elastic Search
      • 队列
  • 版本
    • 5.1
      • 5.1
      • 5.0
      • 4.5
      • 4.4
      • 4.3
      • 4.2
      • 4.1
      • 4.0
      • 3.10
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

命名空间

  • 全局
  • Cake
    • Cache
    • Collection
    • Command
    • Console
    • Controller
    • Core
    • Database
      • Driver
      • Exception
      • Expression
      • Log
      • Query
      • Retry
      • Schema
      • Statement
      • Type
    • Datasource
    • Error
    • Event
    • Form
    • Http
    • I18n
    • Log
    • Mailer
    • Network
    • ORM
    • Routing
    • TestSuite
    • Utility
    • Validation
    • View

类 Query

此类表示一个关系数据库 SQL 查询。查询可以是不同类型的,例如选择、更新、插入和删除。公开用于动态构建每个查询部分、执行查询并将查询转换为特定 SQL 方言的方法。

抽象
命名空间: Cake\Database

常量

  • 字符串
    JOIN_TYPE_INNER ¶
    'INNER'
  • 字符串
    JOIN_TYPE_LEFT ¶
    'LEFT'
  • 字符串
    JOIN_TYPE_RIGHT ¶
    'RIGHT'
  • 字符串
    TYPE_DELETE ¶
    'delete'
  • 字符串
    TYPE_INSERT ¶
    'insert'
  • 字符串
    TYPE_SELECT ¶
    'select'
  • 字符串
    TYPE_UPDATE ¶
    'update'

属性摘要

  • $_connection protected
    Cake\Database\Connection

    要用于执行此查询的连接实例。

  • $_dirty protected
    布尔

    指示此查询的内部状态是否已更改,用于丢弃内存缓存中的内部预处理对象,例如转换后的查询或对已执行语句的引用。

  • $_functionsBuilder protected
    Cake\Database\FunctionsBuilder|null

    用于生成任意 SQL 函数的函数生成器对象实例。

  • $_parts protected
    array<string, mixed>

    用于构建此查询的 SQL 部分列表。

  • $_statement protected
    Cake\Database\StatementInterface|null
  • $_type protected
    字符串

    此查询的类型(选择、插入、更新、删除)。

  • $_typeMap protected
    Cake\Database\TypeMap|null
  • $_valueBinder protected
    Cake\Database\ValueBinder|null

    负责生成查询占位符并将与每个占位符相关联的值临时存储的对象。

  • $connectionRole protected
    字符串

    连接角色('read' 或 'write')

方法摘要

  • __clone() public

    处理清除迭代器并克隆所有表达式和值绑定器。

  • __construct() public

    构造函数。

  • __debugInfo() public

    返回一个数组,可用于描述此对象的内部状态。

  • __toString() public

    返回此查询的字符串表示形式(完整 SQL 语句)。

  • _conjugate() protected

    辅助函数,用于通过组合 QueryExpression 对象来构建条件。

  • _dirty() protected

    将查询标记为脏,从内存缓存中删除任何预处理信息。

  • _expressionsVisitor() protected

    traverseExpressions() 使用的查询部分遍历方法

  • _makeJoin() protected

    返回一个数组,该数组可以传递给描述单个连接子句的 join 方法

  • andWhere() public

    使用 AND 运算符将任何先前定义的条件集连接到提供的列表。此函数接受与方法 where 相同格式的条件列表,因此可以使用数组、表达式对象回调函数或字符串。

  • bind() public

    将查询占位符与值和类型关联。

  • clause() public

    返回存储在指定子句中的任何数据。这对于修改查询的任何内部部分很有用,并且 SQL 方言使用它在查询执行之前相应地转换查询。可以检索的有效子句是:delete、update、set、insert、values、select、distinct、from、join、set、where、group、having、order、limit、offset、union 和 intersect。

  • comment() public

    一个字符串或表达式,将被附加到生成的查询中作为注释

  • epilog() public

    一个字符串或表达式,将被附加到生成的查询

  • execute() public

    编译此查询的 SQL 表示形式并使用配置的连接对象执行它。返回生成的语句对象。

  • expr() public

    返回一个新的 QueryExpression 对象。这是一个使用流畅接口构建复杂查询时的便捷函数。您也可以在子类中覆盖此函数,以在需要时使用更专业的 QueryExpression 类。

  • from() public

    添加一个或多个要用于此查询的 FROM 子句的表。表可以作为字符串数组、表达式对象数组、单个表达式或单个字符串传递。

  • func() public

    返回一个函数生成器对象实例,该实例可用于生成任意 SQL 函数。

  • getConnection() public

    获取用于执行和转换此查询的连接实例。

  • getConnectionRole() public

    返回连接角色('read' 或 'write')

  • getDefaultTypes() public

    获取当前类型映射的默认类型。

  • getTypeMap() public

    返回现有的类型映射。

  • getValueBinder() public

    返回当前使用的 ValueBinder 实例。

  • identifier() public

    创建一个引用标识符的表达式。标识符用于引用字段名,并允许 SQL 编译器应用引号或转义标识符。

  • innerJoin() public

    向查询添加一个 INNER JOIN 子句。

  • join() public

    添加一个或多个表,作为 JOIN 子句用于此查询。表可以作为字符串数组、描述连接部分的数组、具有多个连接描述的数组或单个字符串传递。

  • leftJoin() public

    向查询添加一个 LEFT JOIN 子句。

  • limit() public

    设置要从数据库中检索的记录数量,接受整数或计算结果为整数的表达式对象。在某些数据库中,此操作可能不受支持,或者需要转换查询以限制结果集的大小。

  • modifier() public

    添加一个或多个 SELECT 修饰符,用于 SELECT 语句中。

  • newExpr() public

    返回一个新的 QueryExpression 对象。这是一个使用流畅接口构建复杂查询时的便捷函数。您也可以在子类中覆盖此函数,以在需要时使用更专业的 QueryExpression 类。

  • offset() public

    设置要从原始结果集中跳过的记录数量,这通常用于对大型结果进行分页。接受整数或计算结果为整数的表达式对象。

  • order() public deprecated

    添加一个或多个字段,用于此查询的 ORDER 子句中。字段可以作为字符串数组、表达式对象数组、单个表达式或单个字符串传递。

  • orderAsc() public deprecated

    添加一个带有 ASC 方向的 ORDER BY 子句。

  • orderBy() public

    添加一个或多个字段,用于此查询的 ORDER 子句中。字段可以作为字符串数组、表达式对象数组、单个表达式或单个字符串传递。

  • orderByAsc() public

    添加一个带有 ASC 方向的 ORDER BY 子句。

  • orderByDesc() public

    添加一个带有 DESC 方向的 ORDER BY 子句。

  • orderDesc() public deprecated

    添加一个带有 DESC 方向的 ORDER BY 子句。

  • page() public

    设置您想要的页码。

  • removeJoin() public

    删除已定义的联接。

  • rightJoin() public

    向查询添加单个 RIGHT JOIN 子句。

  • rowCountAndClose() public

    执行此查询的 SQL 语句,并在返回已更改记录的行数之前立即关闭该语句。

  • setConnection() public

    设置用于执行和转换此查询的连接实例。

  • setDefaultTypes() public

    覆盖实现对象中字段的默认类型映射。

  • setTypeMap() public

    如果 $typeMap 是数组,则创建一个新的 TypeMap,否则将其替换为给定的 TypeMap。

  • setValueBinder() public

    覆盖当前值绑定器

  • sql() public

    返回此对象的 SQL 表示形式。

  • traverse() public

    将遍历每个指定的部件。遍历函数可以使用闭包中的变量或实例变量来聚合结果。此函数通常用作遍历将用于构建查询的所有查询部件的方法。

  • traverseExpressions() public

    此函数的工作原理类似于 traverse() 函数,不同之处在于它对整个表达式树进行了全深度遍历。这将对存储在此查询中的每个 ExpressionInterface 对象执行提供的回调函数,无论其嵌套深度如何,以及在查询的任何部分。

  • traverseParts() public

    将遍历提供的部件。

  • type() public

    返回此查询的类型(select、insert、update、delete)。

  • where() public

    添加一个或多个条件,用于此查询的 WHERE 子句中。条件可以表示为一个字段作为键的数组,其中包含比较运算符,数组的值将用于将字段与这样的文字进行比较。最后,条件可以表示为单个字符串或字符串数组。

  • whereInList() public

    添加一个或多个 IN 条件,用于此查询的 WHERE 子句中。

  • whereNotInList() public

    添加一个或多个 NOT IN 条件,用于此查询的 WHERE 子句中。

  • whereNotInListOrNull() public

    添加一个或多个 NOT IN 条件,用于此查询的 WHERE 子句中。这还允许字段使用 IS NULL 条件为 null,因为 null 值会导致 NOT IN 条件始终失败。

  • whereNotNull() public

    方便方法,向查询添加 NOT NULL 条件。

  • whereNull() public

    方便方法,向查询添加 IS NULL 条件。

  • with() public

    向查询添加新的公用表表达式 (CTE)。

方法详细信息

__clone() ¶ public

__clone(): void

处理清除迭代器并克隆所有表达式和值绑定器。

返回
void

__construct() ¶ public

__construct(Cake\Database\Connection $connection)

构造函数。

参数
Cake\Database\Connection $connection

将用于转换和执行此查询的连接对象

__debugInfo() ¶ public

__debugInfo(): array<string, mixed>

返回一个数组,可用于描述此对象的内部状态。

返回
array<string, mixed>

__toString() ¶ public

__toString(): string

返回此查询的字符串表示形式(完整 SQL 语句)。

返回
字符串

_conjugate() ¶ protected

_conjugate(string $part, Cake\Database\ExpressionInterfaceClosure|array|string|null $append, string $conjunction, array<string, string> $types): void

辅助函数,用于通过组合 QueryExpression 对象来构建条件。

参数
string $part

要将新部件追加到的查询部件的名称

Cake\Database\ExpressionInterfaceClosure|array|string|null $append

要追加的表达式或生成器函数。

string $conjunction

用于操作部件的连接类型

array<string, string> $types

用于将值绑定到查询的类型名称的关联数组

返回
void

_dirty() ¶ protected

_dirty(): void

将查询标记为脏,从内存缓存中删除任何预处理信息。

返回
void

_expressionsVisitor() ¶ protected

_expressionsVisitor(mixed $expression, Closure $callback): void

traverseExpressions() 使用的查询部分遍历方法

参数
mixed $expression

查询表达式或表达式数组。

Closure $callback

对在此查询中找到的每个 ExpressionInterface 执行的回调函数。

返回
void

_makeJoin() ¶ protected

_makeJoin(array<string, mixed>|string $table, Cake\Database\ExpressionInterfaceClosure|array|string $conditions, string $type): array

返回一个数组,该数组可以传递给描述单个连接子句的 join 方法

参数
array<string, mixed>|string $table

要联接的表

Cake\Database\ExpressionInterfaceClosure|array|string $conditions

用于联接的条件。

string $type

要使用的联接类型

返回
array

andWhere() ¶ public

andWhere(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): $this

使用 AND 运算符将任何先前定义的条件集连接到提供的列表。此函数接受与方法 where 相同格式的条件列表,因此可以使用数组、表达式对象回调函数或字符串。

需要注意的是,调用此函数时,先前为该查询定义的所有条件集将被视为 AND 运算符的单个参数。此函数不仅会操作最近定义的条件,还会操作所有条件作为一个整体。

当使用数组定义条件时,从每个数组条目创建约束将使用与 where() 函数相同的逻辑。这意味着每个数组条目将使用 AND 运算符与其他条目连接起来,除非您使用其他运算符在数组中嵌套条件。

示例

$query->where(['title' => 'Hello World')->andWhere(['author_id' => 1]);

将产生

WHERE title = 'Hello World' AND author_id = 1

$query
  ->where(['OR' => ['published' => false, 'published is NULL']])
  ->andWhere(['author_id' => 1, 'comments_count >' => 10])

产生

WHERE (published = 0 OR published IS NULL) AND author_id = 1 AND comments_count > 10

$query
  ->where(['title' => 'Foo'])
  ->andWhere(function ($exp, $query) {
    return $exp
      ->or(['author_id' => 1])
      ->add(['author_id' => 2]);
  });

生成以下条件

WHERE (title = 'Foo') AND (author_id = 1 OR author_id = 2)

参数
Cake\Database\ExpressionInterfaceClosure|array|string $conditions

要使用 AND 添加的条件。

array<string, string> $types optional

用于将值绑定到查询的类型名称的关联数组

返回
$this
另请参见
\Cake\Database\Query::where()
\Cake\Database\TypeFactory

bind() ¶ public

bind(string|int $param, mixed $value, string|int|null $type = null): $this

将查询占位符与值和类型关联。

$query->bind(':id', 1, 'integer');
参数
string|int $param

占位符,将被 $value 的引号版本替换

mixed $value

要绑定的值

string|int|null $type optional

映射的类型名称,用于在发送到数据库时进行转换

返回
$this

clause() ¶ public

clause(string $name): mixed

返回存储在指定子句中的任何数据。这对于修改查询的任何内部部分很有用,并且 SQL 方言使用它在查询执行之前相应地转换查询。可以检索的有效子句是:delete、update、set、insert、values、select、distinct、from、join、set、where、group、having、order、limit、offset、union 和 intersect。

这些部件的返回值可能会有所不同。一些子句使用 QueryExpression 在内部存储其状态,一些使用数组,另一些可能使用布尔值或整数。以下是每个子句的返回类型摘要。

  • update: string 要更新的表的名称
  • set: QueryExpression
  • insert: array, 将返回一个包含表和列的数组。
  • values: ValuesExpression
  • select: array, 当没有设置字段时,将返回一个空数组
  • distinct: boolean
  • from: 表数组
  • join: array
  • set: array
  • where: QueryExpression,未设置时返回 null
  • group: array
  • having: QueryExpression,未设置时返回 null
  • order: OrderByExpression,未设置时返回 null
  • limit: integer 或 QueryExpression,未设置时返回 null
  • offset: integer 或 QueryExpression,未设置时返回 null
  • union: array
  • intersect: array
参数
string $name

要返回的子句的名称

返回
mixed
抛出
InvalidArgumentException
当命名的子句不存在时。

comment() ¶ public

comment(string|null $expression = null): $this

一个字符串或表达式,将被附加到生成的查询中作为注释

示例

$query->select('id')->where(['author_id' => 1])->comment('Filter for admin user');

注释内容是原始 SQL,不适合与用户提供的数据一起使用。

参数
string|null $expression optional

要添加的注释

返回
$this

epilog() ¶ public

epilog(Cake\Database\ExpressionInterface|string|null $expression = null): $this

一个字符串或表达式,将被附加到生成的查询

示例

$query->select('id')->where(['author_id' => 1])->epilog('FOR UPDATE');
$query
 ->insert('articles', ['title'])
 ->values(['author_id' => 1])
 ->epilog('RETURNING id');

Epliog 内容是原始 SQL,不适合与用户提供的数据一起使用。

参数
Cake\Database\ExpressionInterface|string|null $expression optional

要追加的表达式

返回
$this

execute() ¶ public

execute(): Cake\Database\StatementInterface

编译此查询的 SQL 表示形式并使用配置的连接对象执行它。返回生成的语句对象。

在内部执行查询会执行几个步骤,第一步是让连接将此对象转换为适合其特定方言的对象,这可能会导致生成不同的查询对象,该对象将是实际执行的对象。紧随其后的是将字面值传递给连接,以便以安全的方式将它们绑定到查询。最后,使用自定义对象装饰生成的语句,以便在需要时为检索到的每一行执行回调。

生成的语句是可遍历的,因此可以像使用数组一样在任何循环中使用它。

此方法可以在查询子类中被重写,以装饰查询执行周围的行为。

返回
Cake\Database\StatementInterface

expr() ¶ public

expr(Cake\Database\ExpressionInterface|array|string|null $rawExpression = null): Cake\Database\Expression\QueryExpression

返回一个新的 QueryExpression 对象。这是一个使用流畅接口构建复杂查询时的便捷函数。您也可以在子类中覆盖此函数,以在需要时使用更专业的 QueryExpression 类。

可以选择传递单个原始 SQL 字符串或表达式数组,这些表达式的任何格式都由 \Cake\Database\Expression\QueryExpression 接受

$expression = $query->expr(); // Returns an empty expression object
$expression = $query->expr('Table.column = Table2.column'); // Return a raw SQL expression
参数
Cake\Database\ExpressionInterface|array|string|null $rawExpression optional

字符串、数组或您想包装在表达式对象中的任何内容

返回
Cake\Database\Expression\QueryExpression

from() ¶ public

from(array|string $tables = [], bool $overwrite = false): $this

添加一个或多个要用于此查询的 FROM 子句的表。表可以作为字符串数组、表达式对象数组、单个表达式或单个字符串传递。

如果传递了数组,则键将用于使用值作为要别名的真实字段来别名表。可以别名字符串、ExpressionInterface 对象甚至其他查询对象。

默认情况下,此函数会将任何传递的参数追加到要从中选择的表的列表中,除非第二个参数设置为 true。

此方法可用于 select、update 和 delete 语句。

示例

$query->from(['p' => 'posts']); // Produces FROM posts p
$query->from('authors'); // Appends authors: FROM posts p, authors
$query->from(['products'], true); // Resets the list: FROM products
$query->from(['sub' => $countQuery]); // FROM (SELECT ...) sub
参数
array|string $tables optional

要添加到列表中的表。此参数可以作为字符串数组、表达式对象数组或单个字符串传递。有关有效调用类型的示例,请参见上面的示例。

bool $overwrite optional

是否使用传递的列表重置表

返回
$this

func() ¶ public

func(): Cake\Database\FunctionsBuilder

返回一个函数生成器对象实例,该实例可用于生成任意 SQL 函数。

示例

$query->func()->count('*');
$query->func()->dateDiff(['2012-01-05', '2012-01-02'])
返回
Cake\Database\FunctionsBuilder

getConnection() ¶ public

getConnection(): Cake\Database\Connection

获取用于执行和转换此查询的连接实例。

返回
Cake\Database\Connection

getConnectionRole() ¶ public

getConnectionRole(): string

返回连接角色('read' 或 'write')

返回
字符串

getDefaultTypes() ¶ public

getDefaultTypes(): array<int|string, string>

获取当前类型映射的默认类型。

返回
array<int|string, string>

getTypeMap() ¶ public

getTypeMap(): Cake\Database\TypeMap

返回现有的类型映射。

返回
Cake\Database\TypeMap

getValueBinder() ¶ public

getValueBinder(): Cake\Database\ValueBinder

返回当前使用的 ValueBinder 实例。

ValueBinder 负责生成查询占位符,并将值临时关联到这些占位符,以便将它们正确地传递给语句对象。

返回
Cake\Database\ValueBinder

identifier() ¶ public

identifier(string $identifier): Cake\Database\ExpressionInterface

创建一个引用标识符的表达式。标识符用于引用字段名,并允许 SQL 编译器应用引号或转义标识符。

该值按原样使用,您可能需要在标识符中使用别名或包含表引用。不要使用此方法注入 SQL 方法或逻辑语句。

示例

$query->newExpr()->lte('count', $query->identifier('total'));
参数
string $identifier

表达式的标识符

返回
Cake\Database\ExpressionInterface

innerJoin() ¶ public

innerJoin(array<string, mixed>|string $table, Cake\Database\ExpressionInterfaceClosure|array|string $conditions = [], array<string, string> $types = []): $this

向查询添加一个 INNER JOIN 子句。

这是通过 join() 构建连接的简写方法。

此方法的参数与 leftJoin() 简写方法相同,请参阅该方法的描述以了解更多详细信息。

参数
array<string, mixed>|string $table

要联接的表

Cake\Database\ExpressionInterfaceClosure|array|string $conditions optional

用于联接的条件。

array<string, string> $types optional

与用于将值转换为相应数据库表示的条件关联的类型列表。

返回
$this

join() ¶ public

join(array<string, mixed>|string $tables, array<string, string> $types = [], bool $overwrite = false): $this

添加一个或多个表,作为 JOIN 子句用于此查询。表可以作为字符串数组、描述连接部分的数组、具有多个连接描述的数组或单个字符串传递。

默认情况下,此函数会将任何传递的参数追加到要连接的表的列表中,除非第三个参数设置为 true。

当没有指定连接类型时,默认情况下使用 INNER JOIN:$query->join(['authors']) 将生成 INNER JOIN authors ON 1 = 1

也可以使用数组键别名连接:$query->join(['a' => 'authors']) 将生成 INNER JOIN authors a ON 1 = 1

可以使用数组符号完整描述和别名连接

$query->join([
    'a' => [
        'table' => 'authors',
        'type' => 'LEFT',
        'conditions' => 'a.id = b.author_id'
    ]
]);
// Produces LEFT JOIN authors a ON a.id = b.author_id

您甚至可以指定一个数组中的多个连接,包括完整描述

$query->join([
    'a' => [
        'table' => 'authors',
        'type' => 'LEFT',
        'conditions' => 'a.id = b.author_id'
    ],
    'p' => [
        'table' => 'publishers',
        'type' => 'INNER',
        'conditions' => 'p.id = b.publisher_id AND p.name = "Cake Software Foundation"'
    ]
]);
// LEFT JOIN authors a ON a.id = b.author_id
// INNER JOIN publishers p ON p.id = b.publisher_id AND p.name = "Cake Software Foundation"

使用条件和类型

条件可以像上面的示例中那样使用字符串来比较列,或者使用包含已引用字面值的字符串来表示。此外,可以使用以数组或表达式对象表示的条件。

在使用数组表示条件时,通常需要将字面值转换为正确的数据库表示。这可以通过使用此函数的第二个参数来实现。

$query->join(['a' => [
    'table' => 'articles',
    'conditions' => [
        'a.posted >=' => new DateTime('-3 days'),
        'a.published' => true,
        'a.author_id = authors.id'
    ]
]], ['a.posted' => 'datetime', 'a.published' => 'boolean'])

覆盖连接

在使用数组符号创建别名连接时,您可以通过在后续调用此函数时使用相同的别名来覆盖先前的连接定义,或者如果此函数的第三个参数设置为 true,则可以将所有先前定义的连接替换为另一个列表。

$query->join(['alias' => 'table']); // joins table with as alias
$query->join(['alias' => 'another_table']); // joins another_table with as alias
$query->join(['something' => 'different_table'], [], true); // resets joins list
参数
array<string, mixed>|string $tables

要连接到查询中的表的列表

array<string, string> $types optional

用于将值绑定到查询的类型名称的关联数组

bool $overwrite optional

是否使用传递的列表重置连接

返回
$this
另请参见
\Cake\Database\TypeFactory

leftJoin() ¶ public

leftJoin(array<string, mixed>|string $table, Cake\Database\ExpressionInterfaceClosure|array|string $conditions = [], array $types = []): $this

向查询添加一个 LEFT JOIN 子句。

这是通过 join() 构建连接的简写方法。

表名可以作为字符串传递,也可以作为数组传递,以防需要对其进行别名

// LEFT JOIN authors ON authors.id = posts.author_id
$query->leftJoin('authors', 'authors.id = posts.author_id');

// LEFT JOIN authors a ON a.id = posts.author_id
$query->leftJoin(['a' => 'authors'], 'a.id = posts.author_id');

条件可以作为字符串、数组或表达式对象传递。在使用数组时,可以将它们与 $types 参数组合起来,以定义如何转换值

$query->leftJoin(['a' => 'articles'], [
     'a.posted >=' => new DateTime('-3 days'),
     'a.published' => true,
     'a.author_id = authors.id'
], ['a.posted' => 'datetime', 'a.published' => 'boolean']);

有关条件和类型的更多详细信息,请参阅 join()。

参数
array<string, mixed>|string $table

要联接的表

Cake\Database\ExpressionInterfaceClosure|array|string $conditions optional

用于联接的条件。

array $types optional

与用于将值转换为相应数据库表示的条件关联的类型列表。

返回
$this

limit() ¶ public

limit(Cake\Database\ExpressionInterface|int|null $limit): $this

设置要从数据库中检索的记录数量,接受整数或计算结果为整数的表达式对象。在某些数据库中,此操作可能不受支持,或者需要转换查询以限制结果集的大小。

示例

$query->limit(10) // generates LIMIT 10
$query->limit($query->newExpr()->add(['1 + 1'])); // LIMIT (1 + 1)
参数
Cake\Database\ExpressionInterface|int|null $limit

要返回的记录数

返回
$this

modifier() ¶ public

modifier(Cake\Database\ExpressionInterface|array|string $modifiers, bool $overwrite = false): $this

添加一个或多个 SELECT 修饰符,用于 SELECT 语句中。

默认情况下,此函数会将任何传递的参数追加到要应用的修饰符列表中,除非第二个参数设置为 true。

示例

// Ignore cache query in MySQL
$query->select(['name', 'city'])->from('products')->modifier('SQL_NO_CACHE');
// It will produce the SQL: SELECT SQL_NO_CACHE name, city FROM products

// Or with multiple modifiers
$query->select(['name', 'city'])->from('products')->modifier(['HIGH_PRIORITY', 'SQL_NO_CACHE']);
// It will produce the SQL: SELECT HIGH_PRIORITY SQL_NO_CACHE name, city FROM products
参数
Cake\Database\ExpressionInterface|array|string $modifiers

要应用于查询的修饰符

bool $overwrite optional

是否使用字段列表重置顺序

返回
$this

newExpr() ¶ public

newExpr(Cake\Database\ExpressionInterface|array|string|null $rawExpression = null): Cake\Database\Expression\QueryExpression

返回一个新的 QueryExpression 对象。这是一个使用流畅接口构建复杂查询时的便捷函数。您也可以在子类中覆盖此函数,以在需要时使用更专业的 QueryExpression 类。

可以选择传递单个原始 SQL 字符串或表达式数组,这些表达式的任何格式都由 \Cake\Database\Expression\QueryExpression 接受

$expression = $query->expr(); // Returns an empty expression object
$expression = $query->expr('Table.column = Table2.column'); // Return a raw SQL expression
参数
Cake\Database\ExpressionInterface|array|string|null $rawExpression optional

字符串、数组或您想包装在表达式对象中的任何内容

返回
Cake\Database\Expression\QueryExpression

offset() ¶ public

offset(Cake\Database\ExpressionInterface|int|null $offset): $this

设置要从原始结果集中跳过的记录数量,这通常用于对大型结果进行分页。接受整数或计算结果为整数的表达式对象。

在某些数据库中,此操作可能不受支持,或者需要转换查询才能限制结果集的大小。

示例

$query->offset(10) // generates OFFSET 10
$query->offset($query->newExpr()->add(['1 + 1'])); // OFFSET (1 + 1)
参数
Cake\Database\ExpressionInterface|int|null $offset

要跳过的记录数

返回
$this

order() ¶ public

order(Cake\Database\ExpressionInterfaceClosure|array|string $fields, bool $overwrite = false): $this

添加一个或多个字段,用于此查询的 ORDER 子句中。字段可以作为字符串数组、表达式对象数组、单个表达式或单个字符串传递。

如果传递了数组,则键将用作字段本身,而值将表示应排序该字段的顺序。当使用相同的字段作为键多次调用时,最后一个排序定义将优先于其他定义。

默认情况下,此函数会将任何传递的参数追加到要选择的字段列表中,除非第二个参数设置为 true。

示例

$query->orderBy(['title' => 'DESC', 'author_id' => 'ASC']);

产生

ORDER BY title DESC, author_id ASC

$query
    ->orderBy(['title' => $query->newExpr('DESC NULLS FIRST')])
    ->orderBy('author_id');

将生成

ORDER BY title DESC NULLS FIRST, author_id

$expression = $query->newExpr()->add(['id % 2 = 0']);
$query->orderBy($expression)->orderBy(['title' => 'ASC']);

以及

$query->orderBy(function ($exp, $query) {
    return [$exp->add(['id % 2 = 0']), 'title' => 'ASC'];
});

两者都将变成

ORDER BY (id %2 = 0), title ASC

查询构建器不会对排序字段/方向进行清理。当传递用户提供的数据到 order() 时,应使用允许的字段/方向列表。

如果需要将复杂表达式作为排序条件,应使用 orderByAsc() 或 orderByDesc()。

参数
Cake\Database\ExpressionInterfaceClosure|array|string $fields

要添加到列表中的字段

bool $overwrite optional

是否使用字段列表重置顺序

返回
$this

orderAsc() ¶ public

orderAsc(Cake\Database\ExpressionInterfaceClosure|string $field, bool $overwrite = false): $this

添加一个带有 ASC 方向的 ORDER BY 子句。

此方法允许将复杂表达式作为排序条件,这与 order() 不同。

排序字段不适合与用户提供的数据一起使用,因为它们不会被查询构建器清理。

参数
Cake\Database\ExpressionInterfaceClosure|string $field

要排序的字段。

bool $overwrite optional

是否重置排序子句。

返回
$this

orderBy() ¶ public

orderBy(Cake\Database\ExpressionInterfaceClosure|array|string $fields, bool $overwrite = false): $this

添加一个或多个字段,用于此查询的 ORDER 子句中。字段可以作为字符串数组、表达式对象数组、单个表达式或单个字符串传递。

如果传递了数组,则键将用作字段本身,而值将表示应排序该字段的顺序。当使用相同的字段作为键多次调用时,最后一个排序定义将优先于其他定义。

默认情况下,此函数会将任何传递的参数追加到要选择的字段列表中,除非第二个参数设置为 true。

示例

$query->orderBy(['title' => 'DESC', 'author_id' => 'ASC']);

产生

ORDER BY title DESC, author_id ASC

$query
    ->orderBy(['title' => $query->newExpr('DESC NULLS FIRST')])
    ->orderBy('author_id');

将生成

ORDER BY title DESC NULLS FIRST, author_id

$expression = $query->newExpr()->add(['id % 2 = 0']);
$query->orderBy($expression)->orderBy(['title' => 'ASC']);

以及

$query->orderBy(function ($exp, $query) {
    return [$exp->add(['id % 2 = 0']), 'title' => 'ASC'];
});

两者都将变成

ORDER BY (id %2 = 0), title ASC

查询构建器不会对排序字段/方向进行清理。当传递用户提供的数据到 order() 时,应使用允许的字段/方向列表。

如果需要将复杂表达式作为排序条件,应使用 orderByAsc() 或 orderByDesc()。

参数
Cake\Database\ExpressionInterfaceClosure|array|string $fields

要添加到列表中的字段

bool $overwrite optional

是否使用字段列表重置顺序

返回
$this

orderByAsc() ¶ public

orderByAsc(Cake\Database\ExpressionInterfaceClosure|string $field, bool $overwrite = false): $this

添加一个带有 ASC 方向的 ORDER BY 子句。

此方法允许将复杂表达式作为排序条件,这与 order() 不同。

排序字段不适合与用户提供的数据一起使用,因为它们不会被查询构建器清理。

参数
Cake\Database\ExpressionInterfaceClosure|string $field

要排序的字段。

bool $overwrite optional

是否重置排序子句。

返回
$this

orderByDesc() ¶ public

orderByDesc(Cake\Database\ExpressionInterfaceClosure|string $field, bool $overwrite = false): $this

添加一个带有 DESC 方向的 ORDER BY 子句。

此方法允许将复杂表达式作为排序条件,这与 order() 不同。

排序字段不适合与用户提供的数据一起使用,因为它们不会被查询构建器清理。

参数
Cake\Database\ExpressionInterfaceClosure|string $field

要排序的字段。

bool $overwrite optional

是否重置排序子句。

返回
$this

orderDesc() ¶ public

orderDesc(Cake\Database\ExpressionInterfaceClosure|string $field, bool $overwrite = false): $this

添加一个带有 DESC 方向的 ORDER BY 子句。

此方法允许将复杂表达式作为排序条件,这与 order() 不同。

排序字段不适合与用户提供的数据一起使用,因为它们不会被查询构建器清理。

参数
Cake\Database\ExpressionInterfaceClosure|string $field

要排序的字段。

bool $overwrite optional

是否重置排序子句。

返回
$this

page() ¶ public

page(int $num, int|null $limit = null): $this

设置您想要的页码。

此方法提供了一个更易于使用的接口来设置想要作为结果的记录集中限制 + 偏移量。如果为空,则限制将默认为现有的限制子句,如果该限制也为空,则将使用 25。

页码必须从 1 开始。

参数
int $num

你想要的页码。

int|null $limit optional

你想要的页码中的行数。如果为 null,将使用当前限制子句。

返回
$this
抛出
InvalidArgumentException
如果页码小于 1。

removeJoin() ¶ public

removeJoin(string $name): $this

删除已定义的联接。

当重新定义联接或想要重新排序联接子句时很有用。

参数
string $name

要移除的联接的别名/名称。

返回
$this

rightJoin() ¶ public

rightJoin(array<string, mixed>|string $table, Cake\Database\ExpressionInterfaceClosure|array|string $conditions = [], array $types = []): $this

向查询添加单个 RIGHT JOIN 子句。

这是通过 join() 构建连接的简写方法。

此方法的参数与 leftJoin() 简写相同,请参考该方法的描述以获取更多详细信息。

参数
array<string, mixed>|string $table

要联接的表

Cake\Database\ExpressionInterfaceClosure|array|string $conditions optional

用于联接的条件。

array $types optional

与用于将值转换为相应数据库表示的条件关联的类型列表。

返回
$this

rowCountAndClose() ¶ public

rowCountAndClose(): int

执行此查询的 SQL 语句,并在返回已更改记录的行数之前立即关闭该语句。

此方法可用于 UPDATE 和 DELETE 查询,但不建议用于 SELECT 查询,也不用于计算记录数。

示例

$rowCount = $query->update('articles')
                ->set(['published'=>true])
                ->where(['published'=>false])
                ->rowCountAndClose();

以上示例将为所有 false 记录的 published 列更改为 true,并返回已更新的记录数。

返回
int

setConnection() ¶ public

setConnection(Cake\Database\Connection $connection): $this

设置用于执行和转换此查询的连接实例。

参数
Cake\Database\Connection $connection

连接实例

返回
$this

setDefaultTypes() ¶ public

setDefaultTypes(array<int|string, string> $types): $this

覆盖实现对象中字段的默认类型映射。

如果需要设置在查询中的多个函数/表达式之间共享的类型映射,此方法很有用。

要添加默认值而不覆盖现有值,请使用 getTypeMap()->addDefaults()

参数
array<int|string, string> $types

要设置的类型数组。

返回
$this
另请参见
\Cake\Database\TypeMap::setDefaults()

setTypeMap() ¶ public

setTypeMap(Cake\Database\TypeMap|array $typeMap): $this

如果 $typeMap 是数组,则创建一个新的 TypeMap,否则将其替换为给定的 TypeMap。

参数
Cake\Database\TypeMap|array $typeMap

如果为数组,则创建 TypeMap,否则设置给定的 TypeMap

返回
$this

setValueBinder() ¶ public

setValueBinder(Cake\Database\ValueBinder|null $binder): $this

覆盖当前值绑定器

ValueBinder 负责生成查询占位符,并将值临时关联到这些占位符,以便将它们正确地传递给语句对象。

参数
Cake\Database\ValueBinder|null $binder

绑定器或 null 以禁用绑定。

返回
$this

sql() ¶ public

sql(Cake\Database\ValueBinder|null $binder = null): string

返回此对象的 SQL 表示形式。

此函数将编译此查询以使其与连接使用的 SQL 方言兼容。此过程可能会添加、删除或更改任何查询部分或内部表达式以使其在目标平台上可执行。

生成的查询可能包含占位符,这些占位符将在执行查询时替换为实际值,因此最适合与准备好的语句一起使用。

参数
Cake\Database\ValueBinder|null $binder optional

生成参数占位符的值绑定器

返回
字符串

traverse() ¶ public

traverse(Closure $callback): $this

将遍历每个指定的部件。遍历函数可以使用闭包中的变量或实例变量来聚合结果。此函数通常用作遍历将用于构建查询的所有查询部件的方法。

回调将接收 2 个参数,第一个是正在迭代的查询部分的值,第二个是该部分的名称。

示例

$query->select(['title'])->from('articles')->traverse(function ($value, $clause) {
    if ($clause === 'select') {
        var_dump($value);
    }
});
参数
Closure $callback

要为每个部分执行的回调

返回
$this

traverseExpressions() ¶ public

traverseExpressions(Closure $callback): $this

此函数的工作原理类似于 traverse() 函数,不同之处在于它对整个表达式树进行了全深度遍历。这将对存储在此查询中的每个 ExpressionInterface 对象执行提供的回调函数,无论其嵌套深度如何,以及在查询的任何部分。

回调将以当前访问的表达式作为第一个参数接收。

参数
Closure $callback

要为在此查询中找到的每个 ExpressionInterface 执行的函数。

返回
$this

traverseParts() ¶ public

traverseParts(Closure $visitor, list<string> $parts): $this

将遍历提供的部件。

遍历函数可以使用闭包或实例变量中的变量来聚合结果。此方法可用于遍历查询部分的子集以渲染 SQL 查询。

回调将接收 2 个参数,第一个是正在迭代的查询部分的值,第二个是该部分的名称。

示例

$query->select(['title'])->from('articles')->traverse(function ($value, $clause) {
    if ($clause === 'select') {
        var_dump($value);
    }
}, ['select', 'from']);
参数
Closure $visitor

为每个部分执行的回调

list<string> $parts

要遍历的查询部分列表

返回
$this

type() ¶ public

type(): string

返回此查询的类型(select、insert、update、delete)。

返回
字符串

where() ¶ public

where(Cake\Database\ExpressionInterfaceClosure|array|string|null $conditions = null, array<string, string> $types = [], bool $overwrite = false): $this

添加一个或多个条件,用于此查询的 WHERE 子句中。条件可以表示为一个字段作为键的数组,其中包含比较运算符,数组的值将用于将字段与这样的文字进行比较。最后,条件可以表示为单个字符串或字符串数组。

使用数组时,每个条目都将使用 AND 运算符连接到条件的其余部分。对该函数的连续调用也将使用 AND 运算符连接指定的新的条件。此外,可以使用包含其他查询对象的表达式对象来表达值。

使用此方法创建的任何条件都可用于任何 SELECT、UPDATE 和 DELETE 类型的查询。

使用运算符的条件

$query->where([
    'posted >=' => new DateTime('3 days ago'),
    'title LIKE' => 'Hello W%',
    'author_id' => 1,
], ['posted' => 'datetime']);

前面的示例生成

WHERE posted >= 2012-01-27 AND title LIKE 'Hello W%' AND author_id = 1

第二个参数用于指定为每个传递的键预期什么类型。有效类型可以使用 Database\Type 类映射的类型。

使用连词嵌套条件

$query->where([
    'author_id !=' => 1,
    'OR' => ['published' => true, 'posted <' => new DateTime('now')],
    'NOT' => ['title' => 'Hello']
], ['published' => boolean, 'posted' => 'datetime']

前面的示例生成

WHERE author_id = 1 AND (published = 1 OR posted < '2012-02-01') AND NOT (title = 'Hello')

可以使用连词任意次嵌套条件。有时,可能希望为同一个键定义两个不同的选项,在这种情况下,可以将每个条件包装在新的数组中

$query->where(['OR' => [['published' => false], ['published' => true]])

将产生

WHERE (published = false) OR (published = true)

请记住,每次调用 where() 并将第三个参数设置为 false(默认值)时,它都将使用 AND 运算符将传递的条件连接到先前存储的列表中。此外,在对该方法的连续调用中使用相同的数组键两次不会覆盖先前的值。

使用表达式对象

$exp = $query->newExpr()->add(['id !=' => 100, 'author_id' != 1])->tieWith('OR');
$query->where(['published' => true], ['published' => 'boolean'])->where($exp);

前面的示例生成

WHERE (id != 100 OR author_id != 1) AND published = 1

其他可作为任何字段条件使用的查询对象。

分多个步骤添加条件

可以使用回调来构建复杂表达式,函数将新 QueryExpression 对象作为第一个参数接收,并将此查询实例作为第二个参数接收。函数必须返回一个表达式对象,该对象将使用 AND 运算符添加到查询的条件列表中。

$query
  ->where(['title !=' => 'Hello World'])
  ->where(function ($exp, $query) {
    $or = $exp->or(['id' => 1]);
    $and = $exp->and(['id >' => 2, 'id <' => 10]);
   return $or->add($and);
  });
  • 前面的示例生成

WHERE title != 'Hello World' AND (id = 1 OR (id > 2 AND id < 10))

条件作为字符串

$query->where(['articles.author_id = authors.id', 'modified IS NULL']);

前面的示例生成

WHERE articles.author_id = authors.id AND modified IS NULL

请注意,使用数组表示法或表达式对象时,所有值将被正确地引用并自动转换为相应的数据库数据类型,从而保护应用程序免受 SQL 注入攻击。但是,键不会被视为不安全的输入,应进行验证/清理。

如果使用字符串条件,请确保你的值已正确引用。你可以做的最安全的事情是永远不要使用字符串条件。

使用可为空的值

使用可为空的值时,可以使用 IS 关键字让 ORM 根据值的类型生成正确的 SQL

$query->where([
    'posted >=' => new DateTime('3 days ago'),
    'category_id IS' => $category,
]);

如果 $category 为 null - 它实际上会将其转换为 category_id IS NULL - 如果它是 4,它会将其转换为 category_id = 4

参数
Cake\Database\ExpressionInterfaceClosure|array|string|null $conditions optional

要过滤的条件。

array<string, string> $types optional

用于将值绑定到查询的类型名称的关联数组

bool $overwrite optional

是否用传递的列表重置条件

返回
$this
另请参见
\Cake\Database\TypeFactory
\Cake\Database\Expression\QueryExpression

whereInList() ¶ public

whereInList(string $field, array $values, array<string, mixed> $options = []): $this

添加一个或多个 IN 条件,用于此查询的 WHERE 子句中。

与 where() 相比,此方法允许空输入,如果你将 allowEmpty 设置为 true。在没有适当的完整性检查的情况下使用它要小心。

选项

  • types - 用于将值绑定到查询的类型名称的关联数组
  • allowEmpty - 允许空数组。
参数
string $field

字段

array $values

值数组

array<string, mixed> $options 可选

选项

返回
$this

whereNotInList() ¶ public

whereNotInList(string $field, array $values, array<string, mixed> $options = []): $this

添加一个或多个 NOT IN 条件,用于此查询的 WHERE 子句中。

与 where() 相比,此方法允许空输入,如果你将 allowEmpty 设置为 true。在没有适当的完整性检查的情况下使用它要小心。

参数
string $field

字段

array $values

值数组

array<string, mixed> $options 可选

选项

返回
$this

whereNotInListOrNull() ¶ public

whereNotInListOrNull(string $field, array $values, array<string, mixed> $options = []): $this

添加一个或多个 NOT IN 条件,用于此查询的 WHERE 子句中。这还允许字段使用 IS NULL 条件为 null,因为 null 值会导致 NOT IN 条件始终失败。

与 where() 相比,此方法允许空输入,如果你将 allowEmpty 设置为 true。在没有适当的完整性检查的情况下使用它要小心。

参数
string $field

字段

array $values

值数组

array<string, mixed> $options 可选

选项

返回
$this

whereNotNull() ¶ public

whereNotNull(Cake\Database\ExpressionInterface|array|string $fields): $this

方便方法,向查询添加 NOT NULL 条件。

参数
Cake\Database\ExpressionInterface|array|string $fields

单个字段、表达式或其列表,这些字段或表达式应不为 null。

返回
$this

whereNull() ¶ public

whereNull(Cake\Database\ExpressionInterface|array|string $fields): $this

方便方法,向查询添加 IS NULL 条件。

参数
Cake\Database\ExpressionInterface|array|string $fields

单个字段、表达式或其列表,这些字段或表达式应为 null。

返回
$this

with() ¶ public

with(Cake\Database\Expression\CommonTableExpressionClosure $cte, bool $overwrite = false): $this

向查询添加新的公用表表达式 (CTE)。

示例

公共表表达式可以作为预先构建的表达式对象传递

$cte = new \Cake\Database\Expression\CommonTableExpression(
    'cte',
    $connection
        ->selectQuery('*')
        ->from('articles')
);

$query->with($cte);

或从闭包中返回,该闭包将接收一个新的公共表表达式对象作为第一个参数,并接收一个新的空白选择查询对象作为第二个参数

$query->with(function (
    \Cake\Database\Expression\CommonTableExpression $cte,
    \Cake\Database\Query $query
 ) {
    $cteQuery = $query
        ->select('*')
        ->from('articles');

return $cte
        ->name('cte')
        ->query($cteQuery);
});
参数
Cake\Database\Expression\CommonTableExpressionClosure $cte

要添加的 CTE。

bool $overwrite optional

是否重置 CTE 列表。

返回
$this

属性详情

$_connection ¶ protected

要用于执行此查询的连接实例。

Type
Cake\Database\Connection

$_dirty ¶ protected

指示此查询的内部状态是否已更改,用于丢弃内存缓存中的内部预处理对象,例如转换后的查询或对已执行语句的引用。

Type
布尔

$_functionsBuilder ¶ protected

用于生成任意 SQL 函数的函数生成器对象实例。

Type
Cake\Database\FunctionsBuilder|null

$_parts ¶ protected

用于构建此查询的 SQL 部分列表。

Type
array<string, mixed>

$_statement ¶ protected

Type
Cake\Database\StatementInterface|null

$_type ¶ protected

此查询的类型(选择、插入、更新、删除)。

Type
字符串

$_typeMap ¶ protected

Type
Cake\Database\TypeMap|null

$_valueBinder ¶ protected

负责生成查询占位符并将与每个占位符相关联的值临时存储的对象。

Type
Cake\Database\ValueBinder|null

$connectionRole ¶ protected

连接角色('read' 或 'write')

Type
字符串
OpenHub
Pingping
Linode
  • 商业解决方案
  • 展示
  • 文档
  • 手册
  • API
  • 视频
  • 报告安全问题
  • 隐私政策
  • 标识和商标
  • 社区
  • 参与进来
  • 问题 (Github)
  • 烘焙坊
  • 精选资源
  • 培训
  • 聚会
  • 我的 CakePHP
  • CakeFest
  • 时事通讯
  • 领英
  • YouTube
  • 脸书
  • 推特
  • Mastodon
  • 帮助和支持
  • 论坛
  • Stack Overflow
  • IRC
  • Slack
  • 付费支持

使用 CakePHP API 文档 生成