我有用户自定义的工作体验表:
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();
});在这里,用户体验数据示例:
----------------------------------------------------------
| 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|
----------------------------------------------------------在本例中,使用id == 1的用户具有7年的工作经验。
2018 - (2017 - 2014) - (2008 - 2004) = 2011用户去年在2018年工作,现在我需要减去上一个工作年度的结果:
2018 - 2011 = 7现在,现有用户有7年的工作经验。
我怎么能用拉拉雄辩来计算定制的工作经验?
发布于 2018-11-10 11:06:59
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;
}
}2)在控制器的行动中使用它:
$userId = 1;
$User = User::findOrFail($userId);
$yearsOfExperience = Workplace::calcExperienceYearsForUser($User);发布于 2018-11-10 12:04:13
我认为你应该在数据库方面做这样的计算。这将是一个更快、更灵活的解决方案。如果有100万用户拥有多个体验条目,并希望选择前10位最有经验的用户,该怎么办?在PHP方面进行这样的计算将非常低效。
下面是一个原始查询(Postgres),它可能完成工作的主要部分:
SELECT SUM(COALESCE(to_year, extract(year from current_date)) - from_year) from experiences;如果您想玩它并测试其他用例:http://sqlfiddle.com/#!9/c9840b/3
其他人可能会说,这是一个过早的优化,但它是一个整体。原始查询非常有能力,应该更经常地使用。
https://stackoverflow.com/questions/53237497
复制相似问题