【问题标题】:save where clause in a variable and use it in laravel query将 where 子句保存在变量中并在 laravel 查询中使用
【发布时间】:2019-01-17 09:24:23
【问题描述】:

我已将所有 where 子句保存在一个变量中,我正在尝试在 laravel 查询中加入该变量,但它不起作用。这是我的代码

$where .= "";
$where .= '->where("product_details.title", '.$request->title.')'; 
$where .= '->where("product_details.id", '.$request->id.')'; 
$results = DB::table('product_details').'$where'.->get();

如何在查询中使用变量?

【问题讨论】:

  • 您的查询是动态的吗?如果不是,你为什么要这样做?另外,您是否尝试过运行它?那么你得到了什么错误?
  • 是的,它是动态的,我得到的错误是“语法错误,意外'->' (T_OBJECT_OPERATOR)”

标签: laravel eloquent


【解决方案1】:

你可以这样使用if条件语句进行动态查询

$results = DB::table('product_details')

if($request->title) {
   $results->where("product_details.title", $request->title);
}
if($request->id) {
   $results->where("product_details.id", $request->id);
}
$result->get();

【讨论】:

    【解决方案2】:

    我不确定您为什么要这样做。以下应该只是工作。

    DB::table('product_details')
        ->where([
            'product_details.title' => $request->title
            'product_details.id' => $request->id
        ])
        ->get(); 
    

    现在,假设您可能并不总是从请求中获得标题或 ID,您也可以这样做

    DB::table('product_details')
        ->when($request->title, function ($query, $title) {
            return $query->where('product_details.title', $title);
        })
        ->when($request->id, function ($query, $id) {
            return $query->where('product_details.id', $id);
        })
        ->get();
    

    【讨论】:

    • 我正在使用 $where 变量,因为我正在处理过滤器,我不想再次编写整个查询
    • 不确定您所说的过滤器是什么意思?但是,如果您的意思是您的请求中可能并不总是存在过滤器,我更新了我的查询。
    • 由于 where 子句接受一个数组,您能否以动态方式构建数组,然后将其放入子句中。所以->where($array)。这将允许您在运行查询之前构建子句并注入它。
    • 当然你也可以这样做:)
    【解决方案3】:

    这不起作用,因为您将文本保存在字符串中,并且输出将在字符串上,您需要将其转换为 eval 试试这个。

    $results = DB::table('product_details')  . eval ($where) .->get();
    

    【讨论】:

    • 我收到此错误“语法错误,意外'->' (T_OBJECT_OPERATOR)”
    • eval 显示转换后的输出尝试 dd 并测试保存 $where 的结果
    • dd($where) 的输出是:"->whereRaw("FIND_IN_SET(?, product_details.industry_id)", [4,5])->whereRaw("FIND_IN_SET(?, product_details. product_category_id)", [1,2]) ◀"
    • 如果你必须使用eval,那很可能是你做错了什么。
    • 使用 eval 确实是一种不好的做法,但正确的形式应该是 $results = eval ('DB::table('product_details')' . $where . '->get()') ;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 2016-05-18
    • 1970-01-01
    • 2019-09-20
    相关资源
    最近更新 更多