0

我开始处理 CakePHP 并通读文档,但有两件事对我来说仍然显得有点笨拙。

  1. 我知道我有一些我想存储的记录的其他框架,但 CakePHP 建议我匿名进行:

    $this->Foo->create(array(...));
    $this->Foo->save();
    

    为什么我不能告诉 CakePHP 要保存哪个 Record,就像在其他所有框架中一样:

    $foo = $this->Foo->create(array(...));
    $foo->save();
    
  2. 我想遍历控制器内的整个 RecordSet。为什么我需要迭代使用

    $foos = $this->Foos->find('all');
    foreach($foos as $foo){
       $foo['Foo'] // ... here we have $foo.
    

    我不明白为什么find()返回一个二维数组并且内部数组中只有记录。为什么这不直接是一个记录数组?

4

1 回答 1

1
  1. $this->Foo 是 Foo 模型的一个实例。当您在其上调用方法时,您正在调用 Foo 模型的该实例的活动记录(如果有的话)上的方法。因此,在告诉 Cake 要保存哪条记录方面,您不需要 - Cake 知道要保存当前的活动记录。

这是您粘贴注释的代码,这可能会有所帮助。

// 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 具有 1 对 1 的关系,并且您将获得 Foo 记录以及它们关联的 Bar 记录。返回的数组将需要 Foo 和 Bar 键,例如:在您的 foreach 循环中,$foo 可能包含:

$foo['Foo']['column1'], $foo['Foo']['column2'], $foo['Bar']['column1'], $foo['Bar']['column2' ]

为了保持一致,当你只从一个表中获取时,它仍然以 $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);
}

此外,对于您只想更新一条记录而不是很多记录的情况,您可以只执行“读取”而不是“查找('all')” - 更多信息请参见下面的链接。

我强烈建议您通读蛋糕烹饪书中的这些页面:

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 的非常重要的基础信息。现在花时间去真正理解它,将来你会省去无数麻烦和代码重构!

于 2012-08-28T22:58:06.367 回答