Laravel雄辩的计算工作经验

And*_*ter 2 laravel eloquent laravel-5.7

我有具有用户工作经历的自定义表:

Schema::create('workplaces', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('user_id');
    $table->foreign('user_id')
          ->references('id')
          ->on('users')
          ->onDelete('cascade');
    $table->string('company')->nullable();
    $table->string('position')->nullable();
    $table->string('description')->nullable();
    $table->smallInteger('from')->nullable();
    $table->smallInteger('to')->nullable();
    $table->timestamps();
});
Run Code Online (Sandbox Code Playgroud)

以下是示例用户体验数据:

----------------------------------------------------------
| user_id | company | position | description | from | to |
----------------------------------------------------------
----------------------------------------------------------
|    1    | Google  | Designer | Lorem ipsum | 2018 |null|
----------------------------------------------------------
----------------------------------------------------------
|    1    |  Yahoo  | Designer | Lorem ipsum | 2014 |2017|
----------------------------------------------------------
----------------------------------------------------------
|    1    |Microsoft| Designer | Lorem ipsum | 2004 |2008|
----------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)

在此示例中,id == 1具有7年工作经验的用户。

2018 - (2017 - 2014) - (2008 - 2004) = 2011
Run Code Online (Sandbox Code Playgroud)

用户去年工作于2018年,现在我需要减去上一个工作年的结果:

2018 - 2011 = 7
Run Code Online (Sandbox Code Playgroud)

现在,当前用户已有7年的工作经验。

我如何使用laravel雄辩地计算自定义工作经验?

num*_*8er 5

1)在app文件名Workplace.php包含以下内容的文件夹中创建模型:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Workplace extends Model 
{
    protected $table = 'workplaces';

    protected $fillable = ['user_id', 'company', 'position', 'description', 'from', 'to'];

    public $timestamps = true;


    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function experienceYears() 
    {
      $from = property_exists($this, 'from') ? $this->from : null;
      $to = property_exists($this, 'to') ? $this->to : null;
      if (is_null($from)) return 0;
      if (is_null($to)) $to = $from; // or = date('Y'); depending business logic
      return (int)$to - (int)$from;
    }

    public static function calcExperienceYearsForUser(User $user) 
    {
        $workplaces = 
            self::with('experienceYears')
                  ->whereUserId($user->id)
                  ->get(['from', 'to']);
        $years = 0;
        foreach ($workplaces AS $workplace) {
          $years+= $workplace->experienceYears;
        }
        return $years;
    }
}
Run Code Online (Sandbox Code Playgroud)

2)将其用于控制​​器的动作:

$userId = 1;
$User = User::findOrFail($userId);
$yearsOfExperience = Workplace::calcExperienceYearsForUser($User);
Run Code Online (Sandbox Code Playgroud)