Skip to content

Commit

Permalink
Add findModel() to QB to create a single Model
Browse files Browse the repository at this point in the history
This method will find and pick the first result matching the query. Only
a single Model will be returned; an invalid Model if the query returns
nothing.
  • Loading branch information
allejo committed Apr 10, 2018
1 parent 753a34c commit 248aa4b
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 5 deletions.
2 changes: 1 addition & 1 deletion models/Permission.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ public static function getPermissionFromName($perm_name)
}

return self::getQueryBuilder()
->find($perm_name, 'name')
->findModel($perm_name, 'name')
;
}

Expand Down
20 changes: 16 additions & 4 deletions src/Model/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,21 @@ public static function escape($string)
return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
}

/**
* Create a single model object from a database result
*
* @param array $result The MySQL row of the model
*
* @return static
*/
public static function createFromDatabaseResult(&$result)
{
$model = new static($result['id'], $result);
$model->storeInCache();

return $model;
}

/**
* Create model objects, given their MySQL entries
*
Expand All @@ -229,10 +244,7 @@ public static function createFromDatabaseResults(&$results)
$models = array();

foreach ($results as $result) {
$model = new static($result['id'], $result);
$model->storeInCache();

$models[] = $model;
$models[] = self::createFromDatabaseResult($result);
}

return $models;
Expand Down
22 changes: 22 additions & 0 deletions src/QueryBuilder/QueryBuilderFlex.php
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,28 @@ public function except($model)
return $this;
}

/**
* Find the first matching model in the database or return an invalid model.
*
* @param mixed $value The value to search for
* @param string $columnName The column name we'll be checking
*
* @return Model
*/
public function findModel($value, $columnName = 'id')
{
$type = $this->modelType;

/** @var array $result */
$result = parent::find($value, $columnName);

if ($result === null) {
return $type::get(0);
}

return $type::createFromDatabaseResult($result);
}

/**
* Only show results from a specific page.
*
Expand Down

0 comments on commit 248aa4b

Please sign in to comment.