CakePHP:限制与模型关联的字段

发布于 2024-12-01 21:05:29 字数 176 浏览 2 评论 0原文

我的一些数据库表中有几个字段,我的 CakePHP 模型永远不需要检索这些字段。是否有某种方法可以设置要在模型级别获取的默认字段集?例如,我从第三方设计的数据库中检索一些数据,每个表有 50 个字段,我使用 5 个。

我知道我可以在 find() 查询时以及模型之间的任何关联时对字段设置限制,但我想知道是否有模型级方法。

I have several fields in some of my database tables that my CakePHP models never need to retrieve. Is there some way to set a default set of fields to fetch at the model level? For instance I retrieve some data from a third party designed database that has 50 fields per table, I use 5.

I know I can set limits on fields at the time of the find() query and at the time of any associations between models, but I was wondering if there was a model-level approach.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

﹎☆浅夏丿初晴 2024-12-08 21:05:29

CakePHP 不提供您在模型级别所描述的开箱即用的内容。也就是说,每个 find() 上都没有使用 defaultFields 的 Model 属性,

正如您所指出的,您可以通过设置 >fields 属性。但是,只有当您跨这些关系之一检索模型时,这才有效。

最后,您将在 find() 中进行设置。您可以通过向模型添加一个属性来最大程度地减少重复:

var $defaultFields = array('Model.field1', 'Model.field2', ...);

然后在您的 find() 中:

$this->Model->find('fields' => $this->Model->defaultFields, ...);

这有明显的限制,但至少提供了一些封装,因此具有灵活性。

注意:更具侵入性的方法可以使用beforeFind();< /代码>。在这种情况下,您不需要调整每个 find()。但您的里程可能会根据您的使用情况而有所不同。

CakePHP does not offer what you describe at the Model level out of the box. That is to say there is no Model property of defaultFields that is used on every find()

As you noted, you could specify this at the association level by setting the fields property. However, this would only work when you were retrieving the Model across one of these relationships.

In the end, you're going to be setting this in your find(). You could minimize repeating yourself by adding a property to your model like so:

var $defaultFields = array('Model.field1', 'Model.field2', ...);

Then in your find():

$this->Model->find('fields' => $this->Model->defaultFields, ...);

This has obvious limitations, but at least provides some encapsulation and therefore flexibility.

Note: A more invasive approach could use beforeFind();. In which case you would not need to adjust every find(). But your mileage may vary based on your usage.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文