CakePHP:限制与模型关联的字段
我的一些数据库表中有几个字段,我的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
CakePHP 不提供您在模型级别所描述的开箱即用的内容。也就是说,每个
find()
上都没有使用defaultFields
的 Model 属性,正如您所指出的,您可以通过设置
>fields
属性。但是,只有当您跨这些关系之一检索模型时,这才有效。最后,您将在
find()
中进行设置。您可以通过向模型添加一个属性来最大程度地减少重复:然后在您的
find()
中:这有明显的限制,但至少提供了一些封装,因此具有灵活性。
注意:更具侵入性的方法可以使用
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 everyfind()
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:Then in your
find()
: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 everyfind()
. But your mileage may vary based on your usage.