【发布时间】:2019-09-08 10:53:09
【问题描述】:
用户的计划存储在invoices 表中。这些计划是按月计算的。
我需要做什么
如果用户的计划到期日期已到并且他们没有更新他们的计划,我想为用户添加一个新行(我不想更新旧的)
问题是
每个用户在每个月更新时,invoices 表中的行数不受限制。现在,当我尝试检索他们的最新行并检查到期日期时,它也会获取这些用户的其他行。
示例
- 我的用户在
invoices中有3 rows - 其中两个已经过期续订,当前一个是
id=3 - 当我尝试使此
id=3过期并为此用户创建id=4时 - 它获取所有
3 rows并向用户发送3 封电子邮件。
代码
public function handle()
{
$invoices = Invoice::where('plan_expire', '<=', Carbon::now())->get();
$current = Carbon::now();
$expiredatetime = $current->addDays(30);
$useType = Type::where('name', 'Free')->first();
foreach($invoices as $invoice)
{
Invoice::create([
'user_id' => $invoice->user->id,
'type_id' => $useType->id,
'amount' => $useType->price,
'status' => 'Approved',
'plan_expire' => $expiredatetime->toDateTimeString(),
]);
Mail::to($invoice->user->email)->send(new UserPlansReset($invoice));
}
}
User model
public function invoices()
{
return $this->hasMany(Invoice::class);
}
Invoice model
protected $fillable = [
'user_id', 'type_id', 'amount', 'status', 'plan_expire',
];
protected $casts = [
'plan_expire' => 'datetime',
];
public function user()
{
return $this->belongsTo(User::class);
}
问题
您知道我如何才能在invoices 表中获取用户的最新行吗?
更新
根据下面的答案,我将代码更改为:
$current = Carbon::now();
$expiredatetime = $current->addDays(30);
$useType = Type::where('name', 'Free')->first();
$users = User::all();
foreach($users as $user){
$latestInvoice = $user->invoices()->latest()->first();
if(!empty($latestInvoice) && $latestInvoice->plan_expire <= Carbon::now()){
Invoice::create([
'user_id' => $user->id,
'type_id' => $useType->id,
'amount' => $useType->price,
'status' => 'Approved',
'plan_expire' => $expiredatetime->toDateTimeString(),
]);
Mail::to($user->email)->send(new UserPlansReset($user));
}
}
现在这个函数会返回
Expected response code 220 but got an empty response
并且不会发送电子邮件。
【问题讨论】: