在 CakePHP 中从模型获取数据的最有效方法是什么?
我是 CakePHP 的新手,仍在了解基础知识。现在,我对从模型(从另一个链接模型内部)获取一个或多个字段的过程感到有点困惑。
到目前为止,我有这个:
$this->user->id = 123;
$this->User->read();
$field1 = $this->User->data['User']['field1'];
$field2 = $this->User->data['User']['field2'];
这看起来非常冗长。
这
$this->user->id = 123;
$field1 = $this->User->field('field1');
$field1 = $this->User->field('field2');
看起来不太长,但会产生两个查询。
在这些情况下,我曾经做什么,在做蛋糕之前:
$this->User = new User(123);
$field1 = $this->User->field1;
$field2 = $this->User->field2;
或者当我想打字时:
this->User = new User(123);
$field1 = $this->User->getFieldOne();
$field2 = $this->User->getFieldTwo();
所以,问题是:我是否缺少 CakePHP 中完成此任务的一些魔力,或者我是否有忍受大量打字?
I'm new to CakePHP, and still figuring out the basics. Right now I'm a bit mystified by the process to get one or more fields from a model (from inside another linked model).
So far, I have this:
$this->user->id = 123;
$this->User->read();
$field1 = $this->User->data['User']['field1'];
$field2 = $this->User->data['User']['field2'];
Which seems awfully verbose.
And this:
$this->user->id = 123;
$field1 = $this->User->field('field1');
$field1 = $this->User->field('field2');
Which seems less long, but results in two queries.
What I used to do in these situations, pre-Cake:
$this->User = new User(123);
$field1 = $this->User->field1;
$field2 = $this->User->field2;
or when I felt like typing:
this->User = new User(123);
$field1 = $this->User->getFieldOne();
$field2 = $this->User->getFieldTwo();
So, the question: am I missing some magic in CakePHP by which to accomplish this task, or do I have to live with typing a lot?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你永远不会相信,但有一条捷径:-)
You will never believe, but there is a short way :-)
或者类似于:
在这两种情况下,$userFields 将是一个包含
User #123
数据的数组。在第二个中,由于第一个参数设置为null
,因此将获取所有字段。第二个参数(可选)设置一个 id,也可以像第一个示例一样提前设置。Or something like:
In both cases, $userFields will be an array with
User #123
data. In the second one, due to the first argument set asnull
, all fields will be fetched. Second argument (optional) sets an id, which can also be pre-set earlier like in the first example.中获取数据
您可以使用“读取”或“查找”或“查询”从模型读取
查找
查询
you can either use 'read' or 'find' or 'query' to get data from model
read
find
query