【问题标题】:Phalcon find with columns parameter returns rows instead modelsPhalcon find with columns 参数返回行而不是模型
【发布时间】:2016-11-18 00:51:09
【问题描述】:

当我使用Model::find() 时,响应是模型的结果集,但是当我添加columns 参数来限制返回的列时,响应是行的结果集。

例子:

// Resultset of Models
$users = \Models\Users\Users::find();

// Resultset of Rows
$users = \Models\Users\Users::find([
        'columns' => 'id, email'
]);

这让我无法调用模型方法。有没有办法在 ::find() 方法中有列限制的模型结果集?我不确定,但这似乎是错误,因为 Phalcon 文档说:

虽然 findFirst() 直接返回被调用类的实例(当有要返回的数据时),但 find() 方法返回一个 Phalcon\Mvc\Model\Resultset\Simple。

并且在使用columns参数时,这条规则也没有例外。

我还要注意 ::find() 的其他参数,例如 conditionorderbind 等都可以正常工作(返回模型)。

Phalcon 1.3.4

【问题讨论】:

  • 选择特定列时,您将始终获得Resultset of Rows,因为Phalcon无法返回您的完整Users模型结构,因此它不会被“识别”为Users对象。

标签: php models phalcon


【解决方案1】:

这不是错误,这是预期的行为。 the docs 中的信息向下滚动到 Parameters 表并阅读 columns 的描述。

如果您需要使用模型方法或关系,则不应指定列。但是如果你追求更好的性能并且不需要模型关系,你应该使用Query Builder

find() 的其余参数,例如条件、顺序等。不会影响您使用模型方法的能力。

findFirst() 方法也像 find() 方法一样工作。此处示例:

未指定列:

News::findFirst(3);

// Output
Models\News Object
(
...

指定列时

News::findFirst([
    'columns' => 'id, created_at'
]);

// Output
Phalcon\Mvc\Model\Row Object
(
    [id] => 1
    [created_at] => 2016-02-02
)

【讨论】:

  • findFirst() 基本上归结为在您的find() 对象上调用getFirst()find()->getFirst()
  • 没错,就是养眼,你也可以使用findFirstByName('Timothy');这样的魔术方法:)
  • 如上所述,这是预期行为,永远不会改变。您仍然可以访问属性,因为这是一个对象。虽然我们或许可以添加一些神奇的 getter/setter。
  • 当谈到 find()findFirst() 我知道行为是相同的。现在我明白为什么使用columns 我无法获得模型。这似乎很明显,但我不认为只有少数列会使其无法创建正常工作的模型。感谢您的解释:)
猜你喜欢
  • 1970-01-01
  • 2020-04-15
  • 1970-01-01
  • 2021-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多