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

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

firstOrCreate add record only if date is different

问题

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

我所做的是:

$currentDate = Carbon::now()->format('Y-m-d');
$ret = Configuration::firstOrCreate(
    [
        'user_email' => $request->input('user_email'),
        'created_at' => $currentDate
    ],
    [
        'price' => $request->input('price'),
        'data' => $json_code,
        'encoded_data' => base64_encode($json_code),
    ]
);

不幸的是,这段代码似乎不起作用,记录总是被添加。
我怀疑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:

$currentDate = Carbon::now()->format('Y-m-d');
$ret = Configuration::firstOrCreate(
    [
        'user_email' => $request->input('user_email'),
        'created_at' => $currentDate
    ],
    [
        'price' => $request->input('price'),
        'data' => $json_code,
        'encoded_data' => base64_encode($json_code),
    ]
);

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

请尝试以下代码:

Configuration::whereDate('created_at', Carbon::now()->format('Y-m-d'))
    ->firstOrCreate(
        [
            'user_email' => $request->input('user_email'),
        ],
        [
            'price' => $request->input('price'),
            'data' => $json_code,
            'encoded_data' => base64_encode($json_code),
        ]
    );
英文:

try this

 Configuration::whereDate('created_at', Carbon::now()->format('Y-m-d')) 
 ->firstOrCreate(
 [ 
   'user_email' => $request->input('user_email'), 
 ] , 
 [ 
   'price' => $request->input('price'), 'data' => $json_code, 
   'encoded_data' => base64_encode($json_code)
 ]); 

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:

确定