firstOrCreate 只在日期不同的情况下添加记录。

huangapple go评论94阅读模式
英文:

firstOrCreate add record only if date is different

问题

我尝试仅在created_at列包含不同日期时添加记录,因此我不需要检查小时和分钟,只需检查年、月和日。

我所做的是:

  1. $currentDate = Carbon::now()->format('Y-m-d');
  2. $ret = Configuration::firstOrCreate(
  3. [
  4. 'user_email' => $request->input('user_email'),
  5. 'created_at' => $currentDate
  6. ],
  7. [
  8. 'price' => $request->input('price'),
  9. 'data' => $json_code,
  10. 'encoded_data' => base64_encode($json_code),
  11. ]
  12. );

不幸的是,这段代码似乎不起作用,记录总是被添加。
我怀疑Laravel也在检查小时和分钟。

是否有一种方法可以使用firstOrCreate仅检查Y-m-d来添加记录?

提前感谢。

英文:

I'm trying to add a record only if created_at column contains a different date, so I don't need to check for hour and minutes, but only for year, month and day.

What I did is:

  1. $currentDate = Carbon::now()->format('Y-m-d');
  2. $ret = Configuration::firstOrCreate(
  3. [
  4. 'user_email' => $request->input('user_email'),
  5. 'created_at' => $currentDate
  6. ],
  7. [
  8. 'price' => $request->input('price'),
  9. 'data' => $json_code,
  10. 'encoded_data' => base64_encode($json_code),
  11. ]
  12. );

unfortunately, this code doesn't seems to work, the record is always added.
I suspect that laravel is doing the check on the hours and minutes also.

Is there a way to use firstOrCreate to add a record checking only Y-m-d?

Thanks in advance.

答案1

得分: 1

请尝试以下代码:

  1. Configuration::whereDate('created_at', Carbon::now()->format('Y-m-d'))
  2. ->firstOrCreate(
  3. [
  4. 'user_email' => $request->input('user_email'),
  5. ],
  6. [
  7. 'price' => $request->input('price'),
  8. 'data' => $json_code,
  9. 'encoded_data' => base64_encode($json_code),
  10. ]
  11. );
英文:

try this

  1. Configuration::whereDate('created_at', Carbon::now()->format('Y-m-d'))
  2. ->firstOrCreate(
  3. [
  4. 'user_email' => $request->input('user_email'),
  5. ] ,
  6. [
  7. 'price' => $request->input('price'), 'data' => $json_code,
  8. 'encoded_data' => base64_encode($json_code)
  9. ]);

huangapple
  • 本文由 发表于 2023年5月29日 16:18:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76355709.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定