[英]Checking if record exists in Laravel not working
i'm doing this to check if the record exists with chasis_number.我这样做是为了检查记录是否存在 chasis_number。 if it doesn't exist insert data and if it does don't insert.
如果它不存在插入数据,如果它不插入。 but it's not working.
但它不起作用。
$chunks = $insert_data->chunk(500);
$owner = Owner::where('chasis_number', '=', request()->get('chasis_number'))->first();
foreach ($chunks as $chunk)
{
if ($owner === null) {
Owner::insert($chunk->toArray());
}
}
The firstOrCreate method will attempt to locate a database record using the given column / value pairs. firstOrCreate 方法将尝试使用给定的列/值对来定位数据库记录。 If the model can not be found in the database, a record will be inserted with the attributes resulting from merging the first array argument with the optional second array argument:
如果在数据库中找不到 model,则将插入一条记录,其中包含将第一个数组参数与可选的第二个数组参数合并后的属性:
https://laravel.com/docs/8.x/eloquent#retrieving-or-creating-models https://laravel.com/docs/8.x/eloquent#retrieving-or-creating-models
Instead of using the first method to determine if any records exist that match your query's constraints, you may use the exists而不是使用第一种方法来确定是否存在任何与查询的约束匹配的记录,您可以使用存在
$ownerExist = Owner::where('chasis_number', '=', request()->get('chasis_number'))->exists();
if ($ownerExist== true) {
Owner::insert($chunk->toArray());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.