您好我在我的数据库中插入一些行,并且我想检查该值是否存在然后不插入,如果没有,则插入它,这是我的控制器:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Input;
use Auth;
use App\User;
use App\Product;
use DB;
class listController extends Controller
{
//
public function getIndex(Request $request){
$user_id=Auth::user()->id;
$list=DB::table('wishlist')
->join('products','wishlist.product_id','=','products.id')
->join('users','wishlist.user_id','=','users.id')
->select('wishlist.id','wishlist.product_id','wishlist.user_id',
'products.id as p_id','products.name','products.salary','products.image_name',
'users.id as u_id')
->where('wishlist.user_id','=',$user_id)
->get();
return view('contents.wishlist')->with('list',$list);
}
public function postIndex(Request $request){
$id=$request->input('id');
$user_id=Auth::user()->id;
$product_id =$request['product_id'];
DB::table('wishlist')->insert(['id'=>$id,'user_id'=>$user_id,'product_id'=>$product_id]);
return redirect('wishlist');
}
public function deleteDeleteProduct(Request $request,$id){
$pro=$request->get('id');
DB::table('wishlist')->where('id',$pro)->delete();
return redirect('wishlist');
}
}
任何人都可以帮我检查它是否存在?
答案 0 :(得分:3)
答案是使用计数函数:
public function postIndex(Request $request){
$id=$request->input('id');
$user_id=Auth::user()->id;
$product_id =$request['product_id'];
$wishlist=DB::table('wishlist')
->where('user_id','=',$user_id)
->where('product_id','=',$product_id)
->count();
if($wishlist > 0){
return redirect('wishlist');
}
else{
DB::table('wishlist')
->insert(['id'=>$id,'user_id'=>$user_id,'product_id'=>$product_id]);
return redirect('wishlist');
}
}
答案 1 :(得分:1)
如果您使用的是mysql
,则可以使用INSERT IGNORE
和laravel's raw queries
唯一的条件是您在表格中的列上定义了 UNIQUE 索引。
DB::insert(
'insert ignore into wishlist (id, user_id, product_id) values (?, ?)',
[$id, $user_id, $product_id]
);
答案 2 :(得分:0)
基本上,您可以从心愿单表中搜索该特定产品的查询。之后,如果查询没有结果,则插入数据。例如,
$found = DB::table('wishlist')->where('name', $product_name)->first();
if (!$found) {
//insert to table
}