为什么我的updateOrInsert无法正常运行laravel

时间:2020-01-13 03:45:01

标签: laravel laravel-5 eloquent

我使用updateOrInsert来避免重复数据,为什么Update函数不起作用并且总是插入数据?

foreach($datas as $data){
                    DB::table('users')->updateOrInsert([
                        'user_connect_id' => $user->connect_id,
                        'description' => $data['description'],
                        'created_by' => $login->name,
                        'modified_by' => $login->name,
                        'created_at' => Carbon::now(),
                    ]);
                }

3 个答案:

答案 0 :(得分:2)

检查updateOrInsert,您需要两个参数,一个是匹配属性,另一个是您的数组。

updateOrInsert(array $attributes, array $values = []) 

示例:

DB::table('users')->updateOrInsert(['user_connect_id' => $user->connect_id],
                     [
                        'user_connect_id' => $user->connect_id,
                        'description' => $data['description'],
                        'created_by' => $login->name,
                        'modified_by' => $login->name,
                        'created_at' => Carbon::now(),
                     ]);

答案 1 :(得分:1)

updateOrInsert方法中有两个参数。updateOrInsert方法接受两个参数:用于查找记录的条件数组,以及包含要更新的列的列和值对的数组。

例如:

DB::table('users')
    ->updateOrInsert(
        ['email' => 'john@example.com', 'name' => 'John'],
        ['votes' => '2']
    );

检查此链接的语法:Laravel Doc

答案 2 :(得分:0)

    // Inseart code
 public function create()
    {
        return view('admin.category.create');
    }
     public function store(Request $request)
        {
            $this->validate($request,[
                'name' => 'required'
            ]);
            $category = new Category();
            $category->name = $request->name;
            $category->slug = str_slug($request->name);
            $category->save();
            Toastr::success('Category Successfully Saved','Success');
            return redirect()->route('admin.category.index');
        }
    // Update code
        public function edit($id)
        {
            $category =Category::find($id);
            return view('admin.category.edit',compact('category'));
        }

       public function update(Request $request, $id)
        {
            $this->validate($request,[
                'name' => 'required|unique:categories'
            ]);
            $category = Category::find($id);
            $category->name = $request->name;
            $category->slug = str_slug($request->name);
            $category->save();
            Toastr::success('Category Successfully Updated','Success');
            return redirect()->route('admin.category.index');
        }