代码之家  ›  专栏  ›  技术社区  ›  Success Man

如果在laravel elokent上完成创建或更新in-loop,如何返回true或false?

  •  0
  • Success Man  · 技术社区  · 6 年前

    我的剧本是这样的:

    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
                    ]);
                }
            }
        }
    }
    

    我希望当创建或更新过程完成时,它将返回true。如果失败,它将返回false

    2 回复  |  直到 6 年前
        1
  •  2
  •   jedrzej.kurylo    6 年前

    如果在Eloquent将更改保存到数据库时出错,将引发异常。您可以简单地用

    public function synch($apiItems)
    {
      try {
    
        // your code goes here
    
        return true;
      } catch (Exception $e) {
        return false;
      }
    }
    

    注:

        2
  •  1
  •   rakib    6 年前

    在代码中添加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;
        }
    }