Свежайшие Пирожки от CakePHP по-русски

Полнейшее руководство CakePHP 1.2 на русском языке, горячие новости и полезные статьи

Сохранение данных

CakePHP делает сохранение данных подобно щелчку пальцами. Данные которые вы хотите сохранить нужно передать в метод save() вашей модели в следующем формате:

Array
(
    [ModelName] => Array
        (
            [fieldname1] => 'value'
            [fieldname2] => 'value'
        )
)

В большинстве случаем вы не должны волноваться за этот формат данных: CakePHP HtmlHelper, FormHelper и метод methods - все упаковывают данные в таком формате. Если вы используете эти помощники, то данные будут доступны для использования как $this->data.

Вот короткий пример метода контроллера, которые использует Модель для сохранения данных в таблице БД:

Простой текст
  1. function edit($id) {
  2. //Была ли форма отправлена?
  3. if(!empty($this->data)) {
  4. //Если данные формы могут быть проверены и сохранены..
  5. if($this->Recipe->save($this->data)) {
  6. //Устанавливаем сообщение и делаем редирект.
  7. $this->Session->setFlash("Recipe Saved!");
  8. $this->redirect('/recipes');
  9. }
  10. }
  11. //Если форма не была отправлена, то находим рецепт для редактирования
  12. //и передаем его в отображение.
  13. $this->set('recipe', $this->Recipe->findById($id));
  14. }

One additional note: when save is called, the data passed to it in the first parameter is validated using CakePHP validation mechanism (see the Data Validation chapter for more information). If for some reason your data isn't saving, be sure to check to see if some validation rules aren't being broken.

There are a few other save-related methods in the model that you'll find useful:

save(array $data = null, boolean $validate = true, array $fieldList = array())

Featured above, this method saves array-formatted data. The second parameter allows you to sidestep validation, and the third allows you to supply a list of model fields to be saved. For added security, you can limit the saved fields to those listed in $fieldList.

The save method also has an alternate syntax:

save(array $data = null, array $params = array())

$params array can have any of the following available options as keys:

Простой текст
  1. array(
  2. 'validate' => true,
  3. 'fieldList' => array(),
  4. 'callbacks' => true //other possible values are false, 'before', 'after'
  5. )

More information about model callbacks is available here

Once a save has been completed, the ID for the object can be found in the $id attribute of the model object - something especially handy when creating new objects.

Простой текст
  1. $this->Ingredient->save($newData);
  2. $newIngredientId = $this->Ingredient->id;

When calling save in a loop, don't forget to call create().

create(array $data = array())

This method resets the model state for saving new information.

If the $data parameter (using the array format outlined above) is passed, the model instance will be ready to save with that data (accessible at $this->data).

saveField(string $fieldName, string $fieldValue, $validate = false)

Used to save a single field value. Set the ID of the model ($this->ModelName->id = $id) just before calling saveField(). When using this method, $fieldName should only contain the name of the field, not the name of the model and field.

For example, to update the title of a blog post, the call to saveField from a controller might look something like this:

Простой текст
  1. $this->Post->saveField('title', 'A New Title for a New Day');

updateAll(array $fields, array $conditions)

Updates many records in a single call. Records to be updated are identified by the $conditions array, and fields to be updated, along with their values, are identified by the $fields array.

For example, to approve all bakers who have been members for over a year, the update call might look something like:

Простой текст
  1. $this_year = date('Y-m-d h:i:s', strtotime('-1 year'));
  2. $this->Baker->updateAll(
  3. array('Baker.approved' => true),
  4. array('Baker.created <=' => "$this_year")
  5. );

The $fields array accepts SQL expressions. Literal values should be quoted manually.

For example, to close all tickets that belong to a certain customer:

Простой текст
  1. $this->Ticket->updateAll(
  2. array('Ticket.status' => "'closed'"),
  3. array('Ticket.customer_id' => 453)
  4. );

saveAll(array $data = null, array $options = array())

Used to save (a) multiple individual records for a single model or (b) this record, as well as all associated records

The following options may be used:

validate: Set to false to disable validation, true to validate each record before saving, 'first' to validate *all* records before any are saved, or 'only' to only validate the records, but not save them.

atomic: If true (default), will attempt to save all records in a single transaction. Should be set to false if database/table does not support transactions. If false, we return an array similar to the $data array passed, but values are set to true/false depending on whether each record saved successfully.

fieldList: Equivalent to the $fieldList parameter in Model::save()

For saving multiple records of single model $data needs to be a numerically indexed array of records like this:

Array
(
	[0] => Array
		(
			[title] => title 1
		)
	[1] => Array
		(
			[title] => title 2
		)
)

The command for saving the above $data array would look like this:

Простой текст
  1. $this->Article->saveAll($data['Article']);

For saving a record along with its related record having a hasOne or belongsTo association the data array should be like this:

Array
(
    [User] => Array
        (
            [username] => billy
        )
    [Profile] => Array
        (
            [sex] => Male
	    [occupation] => Programmer
        )
)

The command for saving the above $data array would look like this:

Простой текст
  1. $this->Article->saveAll($data);

For saving a record along with its related records having hasMany association the data array should be like this:

Array
(
    [Article] => Array
        (
            [title] => My first article
        )
    [Comment] => Array
        (
            [0] => Array
                (
                    [comment] => Comment 1
		    [user_id] => 1
                )
	    [1] => Array
                (
                    [comment] => Comment 2
		    [user_id] => 2
                )
        )
)

The command for saving the above $data array would look like this:

Простой текст
  1. $this->Article->saveAll($data);