为什么拉拉威尔说“;转换nvarchar值时转换失败';[]';到数据类型int”;


Why is Laravel saying "Conversion failed when converting the nvarchar value '[]' to data type int"

我正在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 = [])

我的控制器显示如下:

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

我不明白它为什么一直这样做,尤其是因为我没有要求它查看ID。这里发生了什么?

表格结构:

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

首先,您的表中没有pCategory列。

第二,当您收到all in category参数时,不要将like子句应用于搜索。

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

请参阅int值作为String插入数据库。我的意思是int变量在单引号内。你必须删除它。