CakePHP4のsaveの戻り値

CakePHP4 saveの戻り値

成功するとEntity失敗するとfalseが返ってきます!

@return \Cake\Datasource\EntityInterface|false

saveの内容全部

/**
 * {@inheritDoc}
 *
 * ### Options
 *
 * The options array accepts the following keys:
 *
 * - atomic: Whether to execute the save and callbacks inside a database
 *   transaction (default: true)
 * - checkRules: Whether or not to check the rules on entity before saving, if the checking
 *   fails, it will abort the save operation. (default:true)
 * - associated: If `true` it will save 1st level associated entities as they are found
 *   in the passed `$entity` whenever the property defined for the association
 *   is marked as dirty. If an array, it will be interpreted as the list of associations
 *   to be saved. It is possible to provide different options for saving on associated
 *   table objects using this key by making the custom options the array value.
 *   If `false` no associated records will be saved. (default: true)
 * - checkExisting: Whether or not to check if the entity already exists, assuming that the
 *   entity is marked as not new, and the primary key has been set.
 *
 * ### Events
 *
 * When saving, this method will trigger four events:
 *
 * - Model.beforeRules: Will be triggered right before any rule checking is done
 *   for the passed entity if the `checkRules` key in $options is not set to false.
 *   Listeners will receive as arguments the entity, options array and the operation type.
 *   If the event is stopped the rules check result will be set to the result of the event itself.
 * - Model.afterRules: Will be triggered right after the `checkRules()` method is
 *   called for the entity. Listeners will receive as arguments the entity,
 *   options array, the result of checking the rules and the operation type.
 *   If the event is stopped the checking result will be set to the result of
 *   the event itself.
 * - Model.beforeSave: Will be triggered just before the list of fields to be
 *   persisted is calculated. It receives both the entity and the options as
 *   arguments. The options array is passed as an ArrayObject, so any changes in
 *   it will be reflected in every listener and remembered at the end of the event
 *   so it can be used for the rest of the save operation. Returning false in any
 *   of the listeners will abort the saving process. If the event is stopped
 *   using the event API, the event object's `result` property will be returned.
 *   This can be useful when having your own saving strategy implemented inside a
 *   listener.
 * - Model.afterSave: Will be triggered after a successful insert or save,
 *   listeners will receive the entity and the options array as arguments. The type
 *   of operation performed (insert or update) can be determined by checking the
 *   entity's method `isNew`, true meaning an insert and false an update.
 * - Model.afterSaveCommit: Will be triggered after the transaction is committed
 *   for atomic save, listeners will receive the entity and the options array
 *   as arguments.
 *
 * This method will determine whether the passed entity needs to be
 * inserted or updated in the database. It does that by checking the `isNew`
 * method on the entity. If the entity to be saved returns a non-empty value from
 * its `errors()` method, it will not be saved.
 *
 * ### Saving on associated tables
 *
 * This method will by default persist entities belonging to associated tables,
 * whenever a dirty property matching the name of the property name set for an
 * association in this table. It is possible to control what associations will
 * be saved and to pass additional option for saving them.
 *
 * ```
 * // Only save the comments association
 * $articles->save($entity, ['associated' => ['Comments']]);
 *
 * // Save the company, the employees and related addresses for each of them.
 * // For employees do not check the entity rules
 * $companies->save($entity, [
 *   'associated' => [
 *     'Employees' => [
 *       'associated' => ['Addresses'],
 *       'checkRules' => false
 *     ]
 *   ]
 * ]);
 *
 * // Save no associations
 * $articles->save($entity, ['associated' => false]);
 * ```
 *
 * @param \Cake\Datasource\EntityInterface $entity the entity to be saved
 * @param array|\ArrayAccess|\Cake\ORM\SaveOptionsBuilder $options The options to use when saving.
 * @return \Cake\Datasource\EntityInterface|false
 * @throws \Cake\ORM\Exception\RolledbackTransactionException If the transaction is aborted in the afterSave event.
 */
public function save(EntityInterface $entity, $options = [])
{
    if ($options instanceof SaveOptionsBuilder) {
        $options = $options->toArray();
    }

    $options = new ArrayObject((array)$options + [
        'atomic' => true,
        'associated' => true,
        'checkRules' => true,
        'checkExisting' => true,
        '_primary' => true,
    ]);

    if ($entity->hasErrors((bool)$options['associated'])) {
        return false;
    }

    if ($entity->isNew() === false && !$entity->isDirty()) {
        return $entity;
    }

    $success = $this->_executeTransaction(function () use ($entity, $options) {
        return $this->_processSave($entity, $options);
    }, $options['atomic']);

    if ($success) {
        if ($this->_transactionCommitted($options['atomic'], $options['_primary'])) {
            $this->dispatchEvent('Model.afterSaveCommit', compact('entity', 'options'));
        }
        if ($options['atomic'] || $options['_primary']) {
            $entity->clean();
            $entity->setNew(false);
            $entity->setSource($this->getRegistryAlias());
        }
    }

    return $success;
}

inheritDocを翻訳したもの

オプション

オプション配列には、以下のキーを入力します。

  • atomic: 保存とコールバックをデータベースのトランザクション内で実行するかどうか。
    トランザクション内で実行するかどうか (デフォルト: true)
  • checkRules: 保存前にエンティティのルールをチェックするかどうか、チェックに失敗した場合は
    チェックに失敗した場合は、保存操作を中止します。(デフォルト:true)
  • associated: trueであれば、渡された$entityに定義されているプロパティが見つかった場合、第1レベルの関連するエンティティを保存します。
    プロパティがダーティと判定された場合には、渡された $entity の中で見つかった第1レベルの関連エンティティを保存します。
    がダーティと判定された場合に、渡された $entity に含まれる第1レベルの関連エンティティを保存します。配列の場合は、保存されるアソシエーションのリストとして解釈されます。
    のリストとして解釈されます。このキーを使って、関連付けられたテーブルオブジェクトの保存に異なるオプションを提供することができます。
    テーブルオブジェクトに保存するための異なるオプションを提供することができます。
    false の場合は、関連するレコードは保存されません。(デフォルト: true)
  • checkExisting エンティティが既に存在するかどうかをチェックするかどうかです。
    (デフォルト: true) checkExisting: エンティティが既に存在するかどうかをチェックするかどうか。

イベント

保存時、このメソッドは4つのイベントを起こします。

  • Model.beforeRules: Model.beforeRules: ルールチェックが行われる直前に発生します。
    Model.beforeRules: $options の checkRules キーが false に設定されていない場合、渡されたエンティティのルールチェックが行われる直前に発生します。
    リスナーは、引数として、エンティティ、オプション配列、操作タイプを受け取ります。
    イベントが停止した場合、ルールチェックの結果はイベント自体の結果に設定されます。
  • モデル.afterRules: モデル.afterRules:エンティティに対して checkRules() メソッドが呼び出された直後に発生します。
    モデル.afterRules: エンティティに対して checkRules() メソッドが呼び出された直後に発生します。リスナーは、引数として entity.options 配列と、ルールチェックの結果を受け取ります。
    オプションの配列、ルールチェックの結果、操作タイプを引数として受け取ります。
    イベントが停止した場合、チェック結果はイベント自体の結果に設定されます。
    イベントが停止した場合、チェック結果はイベント自体の結果に設定されます。
  • Model.beforeSave: 永続化されるフィールドのリストが計算される直前にトリガされます。
    モデル.beforeSave: 永続化されるフィールドのリストが計算される直前にトリガされます。このイベントは、エンティティとオプションの両方を引数として
    引数として受け取ります。オプションの配列はArrayObjectとして渡されるため、この配列に変更があった場合は
    の変更はすべてのリスナーに反映され、イベントの終了時に記憶されます。
    イベントの終了時に記憶され、残りの保存操作で使用できるようになります。いずれかのリスナーがfalseを返すと
    を返すと、保存処理が中断されます。イベントが停止した場合
    イベントがイベントAPIを使って停止された場合は、イベントオブジェクトの result プロパティが返されます。
    これは、リスナーの中に独自の保存戦略を実装する場合に便利です。
    リスナーの
  • Model.afterSave: 挿入や保存が成功した後にトリガーされます。
    リスナーはエンティティとオプションの配列を引数として受け取ります。実行された操作のタイプ
    エンティティのメソッド isNew をチェックすることで、実行された操作の種類(挿入または更新)を判断できます。
    真は挿入を意味し、偽は更新を意味します。
  • Model.afterSaveCommit: トランザクションがコミットされた後に実行されます。
    アトミックセーブの場合、リスナーは引数としてエンティティとオプション配列
    を引数として受け取ります。

このメソッドは、渡されたエンティティをデータベースに挿入する必要があるか
データベースに挿入または更新する必要があるかどうかを判断します。これは、エンティティの isNew メソッドをチェックすることで行われます。
メソッドをチェックします。保存されるエンティティが errors() メソッドから空でない値を返した場合,そのエンティティは保存されません。
メソッドから空でない値が返された場合は保存されません。

関連テーブルへの保存

このメソッドはデフォルトで、関連付けられたテーブルに属するエンティティを永続化します。
このテーブルの関連付けに設定されているプロパティ名に一致するダーティなプロパティがあると
ダーティなプロパティが設定されると、関連するテーブルに属するエンティティがデフォルトで永続化されます。どのような関連付けを保存するかを制御することができます。
また、保存するための追加オプションを渡すこともできます。

// コメントの関連付けだけを保存します
$articles->save($entity, ['assisted' => ['Comments']]) を使用します。

// 会社、従業員、それぞれの関連するアドレスを保存します。
// 従業員については、エンティティのルールをチェックしません
$companies->save($entity, [
'関連住所' => [
    'Employees' => [
    'associated' => ['Addresses'],
    'checkRules' => false
    ]
]
]);

// 関連付けをしないで保存します
$articles->save($entity, ['associated' => false]) を使用します。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です