我开始解决CakePHP并阅读文档,但有两件事对我来说似乎有些笨拙。
我知道其他框架,我有一个某些记录,我想存储,但CakePHP建议我匿名进行:
$this->Foo->create(array(...));
$this->Foo->save();
为什么我不能告诉CakePHP要保存哪个记录,就像在其他所有框架中一样:
$foo = $this->Foo->create(array(...));
$foo->save();
我想遍历Controller内部的整个RecordSet。为什么我需要使用
进行迭代$foos = $this->Foos->find('all');
foreach($foos as $foo){
$foo['Foo'] // ... here we have $foo.
我不明白为什么find()
返回一个二维数组,并且内部数组中只有记录。为什么这不直接是一系列记录?
答案 0 :(得分:1)
以下是您粘贴评论的代码,这可能有所帮助。
// Prepare this instance of the Foo model to save a new record
$this->Foo->create(array(...));
// Save the new record that we have just prepared
$this->Foo->save();
另一种方式......
// Call the create method on this instance of the Foo model, and return what?
// Return another instance of the Foo model?
// Why not just continue using the instance we already have, ie, $this->Foo
$foo = $this->Foo->create(array(...));
// Call the save method on the duplicate instance of the Foo model that was
// returned from the create method?
$foo->save();
// Why did 'create' need to return a duplicate instance of the model to do a save???
// Why not call the save on the same instance of the Foo model that we used to call the create?
第2点。这基本上是为了保持一致性。通常,您将从多个表中返回数据,并相互链接。让我们说表Foo和Bar有一对一的关系,你得到Foo记录及其相关的Bar记录。返回的数组将需要Foo和Bar键,例如:在你的foreach循环中,$ foo可能包含:
$ foo ['Foo'] ['column1'],$ foo ['Foo'] ['column2'],$ foo ['Bar'] ['column1'],$ foo ['Bar'] [ '列2']
为了保持一致,当你只从一个表中获取时,它仍然以$ foo ['Foo'] ['column1']的形式返回,就像你从多个表中获取连接数据一样。
编辑:在回复您的评论时,请说明您有以下代码:
$foos = $this->Foos->find('all');
假设您想在返回的数组的每一行上调用一些模型方法,有几种方法可以做到。一种方式是:
// This is code for the controller
$this->Car->find('all');
foreach($cars as $car){
$this->Car->driveTwoMiles($car); // the driveTwoMiles would be in your model class
}
所以在你的模型中,你有一个方法:
// This would be a method in your model class
function driveTwoMiles($car){
$this->id = $car['Car']['id']; // set the active record
// we are now inside the model, so $this->id is the same as calling $this->Car->id from the controller
// Do whatever you want here. You have an active record, and your $car variable, holding data
$this->Post->saveField('distance_driven', $car['Car']['distance_driven']+2);
}
此外,对于您只想更新一条记录而不是更多记录的情况,您可以只执行“阅读”而不是“查找('全部')” - 以下链接中的更多信息。
我强烈建议您在蛋糕烹饪书中一直阅读这些页面:
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html - 检索数据
http://book.cakephp.org/2.0/en/models/saving-your-data.html - 保存数据
http://book.cakephp.org/2.0/en/models/deleting-data.html - 删除数据
所有这些都包含有关如何使用Cake Models的非常重要的基础信息。现在花些时间真正理解它,你将来会为自己省去无数头痛和代码重新考虑因素!