Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用eloquent检索由类SQL运算符组成的集合_Php_Mysql_Laravel_Eloquent - Fatal编程技术网

Php 使用eloquent检索由类SQL运算符组成的集合

Php 使用eloquent检索由类SQL运算符组成的集合,php,mysql,laravel,eloquent,Php,Mysql,Laravel,Eloquent,我在我的网站上有一个搜索表;当用户输入一个搜索词时,它被传递到URL查询字符串中。我想使用这些数据来使用类似SQL的操作符构建一个集合 我用搜索方法设置了一个“产品”控制器 public function search() { $searchTerm = request('s'); $products = Product::where('productTitle', 'LIKE', '%{{$searchTerm}}%'); return $products;

我在我的网站上有一个搜索表;当用户输入一个搜索词时,它被传递到URL查询字符串中。我想使用这些数据来使用类似SQL的操作符构建一个集合

我用搜索方法设置了一个“产品”控制器

public function search()
{

    $searchTerm = request('s');

    $products  = Product::where('productTitle', 'LIKE', '%{{$searchTerm}}%');

    return $products;

    return view('search', [
        'searchTerm' => $searchTerm,
        'products' => $products
    ]);
}
但是,当我运行此操作时,我收到以下错误:

无法创建Illumb\Database\Eloquent\Builder类的对象 转换为字符串


首先,您不需要字符串中的
{{}
,只需执行以下操作:

$products  = Product::where('productTitle', 'LIKE', "%$searchTerm%")->get();
请注意,末尾的
->get()
是返回集合的内容。

执行此操作

public function search()
{

    $searchTerm = request('s');

    $data['products']  = Product::where('productTitle', 'LIKE', '%$searchTerm%')->get();

        return view('search',$data);
}
这是返回视图中的数据。然后在视图上启动
@foreach@endforeach
以显示如下结果:

@extends('app.layout')

@section('content')

  @foreach( $products as $p)

    {{ $p->searchTerm }}
    {{ $p->products }}

  @endforeach

@endsection

这就是我让你跑的吗?您必须使用
双引号,才能使
$searchTerm
的值成为它所包含的值
“%$searchTerm%”
将等于
“%$searchTerm%”
,而
“%$searchTerm%”
将等于
“%querystring%”
。因此,要计算引号内的变量,您必须使用双引号而不是单引号,我希望我很清楚。@MichaelBarley您可以尝试使用
dd($searchTerm)
调试
$searchTerm
$searchTerm>中得到的结果。您只是进行了一次查询,但没有触发它。最后使用get()函数。这里有get()函数。返回并再次检查代码