如果数据库中存在值,请不要保存Laravel

时间:2018-06-18 05:42:43

标签: php laravel laravel-5.5

我创建了一个愿望清单,用户可以保存自己的产品并保存。我想要的是用户不能多次保存产品。 所以,我正在做的是,如果DB中存在product_id,我不想保存新记录。

这是我的代码,我做错了什么?

public function addWishlist(Wishlist $wishlist) {        
    $wishlist->user_id = request('user_id');
    $wishlist->product_id = request('product_id');

    if(DB::table('wishlists')->where('product_id' !== $wishlist->product_id)) {
        $wishlist->save();
        return redirect()->back();
    }
}

4 个答案:

答案 0 :(得分:1)

这个怎么样

public function addWishlist(Wishlist $wishlist) {  
    $userId = request('user_id');
    $productId = request('product_id');

    $found = Wishlist::where('user_id', $userId)->where('product_id', $productId)->count();

    if($found == 0) {
        $wishlist->user_id = $userId;
        $wishlist->product_id = $productId;
        $wishlist->save();
        return redirect()->back();
    }
}

答案 1 :(得分:0)

public function addWishlist(Wishlist $wishlist) {   

    if(DB::table('wishlists')->where(['user_id'=>$user_id,'product_id'=>$wishlist->product_id])->exists()){
         // record already exist 
         return redirect()->back();
    }else{
         // record not exist , save the record
         $withlist = new Wishlist();     
         $wishlist->user_id = request('user_id');
         $wishlist->product_id = request('product_id');
         $wishlist->save();
         return redirect()->back();
    }
}

答案 2 :(得分:0)

您可以使用firstOrNew,但需要查看user_idproduct_id组合

    $wishlist::firstOrNew(array('user_id' => request('user_id'),'product_id'=>request('product_id')));
    $wishlist->user_id = request('user_id');
    $wishlist->product_id = request('product_id');
    $wishlist->save();
    return redirect()->back();

答案 3 :(得分:0)

您是否尝试过firstOrCreate()

 $user = User::firstOrCreate(['email' => $email])