为什么Laravel说“将nvarchar值'[]'转换为数据类型int时转换失败”

问题描述 投票:1回答:2

我正在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)
);
php sql-server laravel laravel-5
2个回答
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]);
}

0
投票

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

热门问题
推荐问题
最新问题