0

我的 laravel 项目中有以下表格

users
profiles
fitness_reports

每个配置文件都属于一个用户,每个健身报告都属于一个配置文件。用户可以拥有一个个人资料和多个通过个人资料 ID 连接的健身报告。这是向用户显示每周报告。

Profiles 表包含 user_id、dob、age、height、weight、腰部、臀部、颈部、executive_level 等列,这些列由用户输入并正确存储在配置文件表中。这工作正常。

Fitness_reports 表具有 profile_id、'bmi'、'bmr'、'bai'、'weight_status'、'fat_us'、'fat_bmi'、'fat_mass'、'lean_mass'、'fat_category'等列。所有这些字段都是计算字段,只要配置文件表中有更新,就需要自动计算。

以前我有一个带有计算字段的模型,在下面可以正常工作

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));
   }
}

但这不起作用。什么都没有得救。每当用户更新个人资料中的当前信息时,如何保存不同的报告。

任何帮助表示赞赏

4

2 回答 2

0

你可以尝试这样的事情:

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-04T00:23:55.117 回答
0

你想创建一个新的Fitness Report每次Profile更新所以你可以使用event handlers.Eloquent Models

将事件处理程序设置为Prfile Model updatedevent 以保存新的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

于 2018-10-04T01:30:57.347 回答