2016-04-30 42 views
1

我正在Laravel中编写搜索函数,并且它会抛出以下错误:QueryException in Connection.php line 651: SQLSTATE[22018]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Conversion failed when converting the nvarchar value '[]' to data type int. (SQL: select * from Product where pID = [])为什么Laravel说“将nvarchar值[]'转换为数据类型int时出现转换失败”

我的控制器,内容如下:

public function productSearch(Request $request){ 
     $searchResult; 
     if($request->input('category') == 'all'){ 
      $searchResult = Product::where("pCategory", "like", '%') 
       ->where('pName', 'like', $request->input('search'))->get(); 
     }else{ 
      $searchResult = Product::where("pCategory", "like", $request->input('category')) 
       ->where('pName', 'like', $request->input('search'))->get(); 
     } 
     //dd($searchResult); 
     return view('products',['products' => $searchResult]); 
    } 

和模型如下:

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Product extends Model 
{ 
    protected $table = 'Product'; 
    protected $primaryKey = 'pID'; 
    // 

    public function orderDetails(){ 
     return $this->hasMany('App\OrderDetail','ProductID','pID'); 
    } 

} 

我不明白为什么它一直这样做,尤其是因为我不要求它看看身份证。这里发生了什么?

表结构:

CREATE TABLE [dbo].[Product] (
    [pID]   INT   IDENTITY (1, 1) NOT NULL, 
    [pName]  VARCHAR (50) NOT NULL, 
    [pBrand]  VARCHAR (20) NOT NULL, 
    [pCurrentType] VARCHAR (10) NOT NULL, 
    [pVoltage]  FLOAT (53)  NOT NULL, 
    [pPrice]  FLOAT (53)  NOT NULL, 
    [pStock]  INT   NOT NULL, 
    [ImagePath] NVARCHAR (500) NULL, 
    CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED ([pID] ASC) 
); 

回答

2

首先,你不要在你的表有pCategory列。

其次,在收到所有类别参数时,不要使用类似子句进行搜索。

public function productSearch(Request $request){ 
    $searchResult = new Product; 

    if($request->has('search') && !empty($request->get('search')) && $request->get('search') !== 'all') { 
     $searchResult = $searchResult->where("pName", "like", '%'.$request->get('search')); 
    } 

    $searchResult = $searchResult->get(); 
    return view('products',['products' => $searchResult]); 
} 
相关问题