Cake\ORM\Table::findOrCreate PHP Method

findOrCreate() public method

A find() will be done to locate an existing record using the attributes defined in $search. If records matches the conditions, the first record will be returned. If no record can be found, a new entity will be created with the $search properties. If a callback is provided, it will be called allowing you to define additional default values. The new entity will be saved and returned. If your find conditions require custom order, associations or conditions, then the $search parameter can be a callable that takes the Query as the argument, or a \Cake\ORM\Query object passed as the $search parameter. Allowing you to customize the find results. ### Options The options array is passed to the save method with exception to the following keys: - atomic: Whether to execute the methods for find, save and callbacks inside a database transaction (default: true) - defaults: Whether to use the search criteria as default values for the new entity (default: true)
public findOrCreate ( array | Query $search, callable $callback = null, array $options = [] ) : Cake\Datasource\EntityInterface
$search array | Query The criteria to find existing records by. Note that when you pass a query object you'll have to use the 2nd arg of the method to modify the entity data before saving.
$callback callable A callback that will be invoked for newly created entities. This callback will be called *before* the entity is persisted.
$options array The options to use when saving.
return Cake\Datasource\EntityInterface An entity.
    public function findOrCreate($search, callable $callback = null, $options = [])
    {
        $options += ['atomic' => true, 'defaults' => true];
        if ($options['atomic']) {
            return $this->connection()->transactional(function () use($search, $callback, $options) {
                return $this->_processFindOrCreate($search, $callback, $options);
            });
        }
        return $this->_processFindOrCreate($search, $callback, $options);
    }