Se agrega funcionalidad a los modelos para que controlen I/O de la base de datos
This commit is contained in:
@ -3,6 +3,7 @@ namespace ProVM\Money;
|
||||
|
||||
use ProVM\Common\Alias\Model;
|
||||
use ProVM\Common\Define\Model\DateTime;
|
||||
use ProVM\Common\Factory\Model as ModelFactory;
|
||||
|
||||
/**
|
||||
* @property Currency $currency_id
|
||||
@ -10,10 +11,11 @@ use ProVM\Common\Define\Model\DateTime;
|
||||
* @property double $value
|
||||
* @property Currency $base_id
|
||||
*/
|
||||
class Value {
|
||||
class Value extends Model {
|
||||
use DateTime;
|
||||
|
||||
public static $_table = 'values';
|
||||
public static $_id_column = ['currency_id', 'base_id', 'date_time'];
|
||||
|
||||
protected $currency;
|
||||
public function currency(): ?Currency {
|
||||
@ -29,4 +31,43 @@ class Value {
|
||||
}
|
||||
return $this->base;
|
||||
}
|
||||
|
||||
protected static $fields = ['currency_id', 'date_time', 'value', 'base_id'];
|
||||
public static function add(ModelFactory $factory, $info) {
|
||||
$input = array_intersect_key((array) $info, array_combine(self::$fields, self::$fields));
|
||||
$value = $factory->find(Value::class)->where([['currency_id', $input['currency_id']], ['date_time', $input['date_time']], ['base_id', $input['base_id']]])->one();
|
||||
$created = false;
|
||||
$result = (object) compact('input', 'value', 'created');
|
||||
if (!$value) {
|
||||
$value = $factory->create(Value::class, $input);
|
||||
$created = $value->save();
|
||||
$result->created = $created;
|
||||
}
|
||||
$result->value = $value->asArray();
|
||||
return $result;
|
||||
}
|
||||
public function edit($info) {
|
||||
$data = array_intersect_key((array) $info, array_combine(self::$fields, self::$fields));
|
||||
$edited = false;
|
||||
foreach ($data as $field => $value) {
|
||||
if ($this->{$field} != $value) {
|
||||
if ($field == 'currency_id' or $field == 'base_id') {
|
||||
continue;
|
||||
}
|
||||
$this->{$field} = $value;
|
||||
$edited = true;
|
||||
}
|
||||
}
|
||||
if ($edited) {
|
||||
$edited = $this->save();
|
||||
}
|
||||
return $edited;
|
||||
}
|
||||
public function asArray(): array {
|
||||
$output = parent::asArray();
|
||||
$output['currency'] = $this->currency()->asArray();
|
||||
$output['base'] = $this->base()->asArray();
|
||||
$output['date_time'] = $this->dateTime()->format('Y-m-d H:i:s');
|
||||
return $output;
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user