【发布时间】:2018-03-08 17:52:54
【问题描述】:
将计算字段存储在数据库中的最佳做法是什么。
例如,假设一个表格具有高度、重量、bmi 字段
用户输入身高体重值并自动填充 bmi 字段。如何通过表单实现这一点。
体重指数公式 $bmi = 体重 / (身高 * 身高)
尝试了以下 配置文件模型
protected $table = 'profiles';
protected $fillable = ['user_id', 'weight', 'height', 'dob', 'age', 'bmi'];
public function user(){
return $this->belongsTo(User::class, 'user_id');
}
protected static function boot() {
parent::boot();
static::saving(function($model){
$model->bmi = $model->weight / ($model->height * $model->height);
$model->age = (date('Y') - date('Y',strtotime($model->dob)));
});
}
配置文件控制器
public function store(Request $request)
{
$profile = new Profile();
$profile->weight = $request->get('weight');
$profile->height = $request->get('height');
$profile->dob = $request->get('dob');
$profile->age;
$profile->bmi;
$profile->save();
return back()->with('success', 'Your profile has been updated.');
}
但是我收到一个错误
Illuminate \ Database \ QueryException (42S22)
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'weight' in 'field list' (SQL: insert into `users` (`weight`, `height`, `dob`, `bmi`, `age`, `created_by`, `updated_by`, `updated_at`, `created_at`) values (60, 175, 1988-04-03, 0.0019591836734694, 30, 2, 2, 2018-03-08 20:06:02, 2018-03-08 20:06:02))
【问题讨论】:
-
在将值插入表之前,您需要手动计算bmi并将其分配给
$yourObject->bmi = $calculatedBmi -
那么我可以使用相同的论坛吗la $calculateBmi = $request->weight / ($request->height * $request->height)
-
是的,您可以使用相同的 $request 对象值
标签: laravel