在我的laravel项目中有以下表
users
profiles
fitness_reports每个简档属于一个用户,每个健康报告属于一个简档。用户可以具有通过简档id连接的一个简档和多个健身报告。这是向用户显示每周报告。
Profiles表具有由用户输入并正确存储在profiles表中的列,如user_id、道布、年龄、身高、体重、腰部、臀部、颈部、exercise_level。这可以很好地工作。
fitness_reports表有如下列: profile_id、'bmi‘、'bmr’、'bai‘、'weight_status’、'fat_us‘、'fat_bmi’、'fat_mass‘、'lean_mass’、'fat_category‘。所有这些字段都是计算字段,只要profiles表中有更新,就需要自动计算它们。
以前,我有一个带有计算字段的单一模型,可以很好地使用下面的
public function getBmiAttribute() {
return ($this->weight / ($this->height * $this->height));
}然后使用控制器代码将其保存在相同的配置文件模型中
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.');
}但是现在,我们已经创建了一个单独的fitness_reports表来跟踪每周报告。如何对此场景执行相同的操作。
我已经试过了
use App\Models\Profile;
class FitnessReport extends Model
{
.....
public function getBmiAttribute($value)
{
return ($this->weight / ($this->height * $this->height));
}
}但这并不管用。什么都救不了。如何在用户更新个人资料中的当前信息时保存不同的报告。
任何帮助我们都将不胜感激
发布于 2018-10-04 08:23:55
您可以尝试如下所示:
class Profile extends Model
{
// since this is really a function of the profile data
public function getBmiAttribute()
{
return ($this->weight / ($this->height * $this->height));
}
}然后,当您存储FitnessReport时:
public function store(Request $request)
{
$profile = Auth::user()->profile;
$report = new FitnessReport();
$report->bmi = $profile->bmi;
$report->save();
return back()->with('success', 'Fitness report saved.');
}..。或者从您需要保存报告的任何位置执行类似的操作。
发布于 2018-10-04 09:30:57
您希望每次更新Profile时都创建一个新的Fitness Report,以便可以使用Eloquent Models的event handlers。
将事件处理程序设置为Prfile Model updated事件以保存新的Fitness Report。
class Profile extends Model
{
protected static function boot()
{
parent::boot(); // TODO: Change the autogenerated stub
parent::updated(function ($profile) {
FitnessReport::create([
'profile_id' => $profile->id,
'bmi' => $profile->weight / ( $profile->height * $profile->height ),
...
... // other necessary fields
]);
});
}
// relationship to fitness reports.
public function fitnessReports()
{
return this->hasMany(FitnessReport::class);
}
}每次创建新模型时都会发生这种情况。bmi将自动设置为模型并保存。
尝试用updating event做同样的事情
https://stackoverflow.com/questions/52635841
复制相似问题