如果在 laravel eloquent 上完成循环创建或更新,我如何 return 是真还是假?

How can I return true or false if create or update in loop finished on the laravel eloquent?

我的脚本是这样的:

public function synch($apiItems)
{
    $itemsLocal = $this->item->get();
    foreach ($apiItems as $key) {
        $check = $itemsLocal->filter(function ($item) use ($key) {
            return $item->code == $key->Code;
        });
        if ($check->count() < 1) {
            $this->item->create([
                'code' => $key->Code,
                'description' => $key->Description,
                'attribute_code' => $key->Attribute_Code,                
                'flag' => $key->Flag
            ]);
        } 
        else {
            if($key->Flag === false) {
                $this->item->where(['code' => $check->first()->code])->update([
                    'description' => $key->Description,
                    'attribute_code' => $key->Attribute_Code,
                    'flag' => $key->Flag
                ]);
            }
        }
    }
}

我希望创建或更新过程完成后 return 为真。如果失败,它将 return false

我该怎么做?

在您的代码中添加 try catch。更改如:

public function synch($apiItems)
{
    try{
        $itemsLocal = $this->item->get();
        foreach ($apiItems as $key) {
            $check = $itemsLocal->filter(function ($item) use ($key) {
                return $item->code == $key->Code;
            });
            if ($check->count() < 1) {
                $this->item->create([
                    'code' => $key->Code,
                    'description' => $key->Description,
                    'attribute_code' => $key->Attribute_Code,                
                    'flag' => $key->Flag
                ]);
            } 
            else {
                if($key->Flag === false) {
                    $this->item->where(['code' => $check->first()->code])->update([
                        'description' => $key->Description,
                        'attribute_code' => $key->Attribute_Code,
                        'flag' => $key->Flag
                    ]);
                }
            }
        }

        return true;
    } catch (Exception $e) {
        return false;
    }
}

如果Eloquent保存修改到数据库时出现错误,将抛出异常。当抛出异常时,您可以简单地用 try/catch 和 return false 包装您的代码。

public function synch($apiItems)
{
  try {

    // your code goes here

    return true;
  } catch (Exception $e) {
    return false;
  }
}

注意:当您在一个循环中进行多次更新时,请确保整个过程作为单个数据库事务的一部分发生,这样您就不会结束更新部分更新的数据。一个例子是当一些项目被创建时,但随后发生错误,其余的被跳过。