dongshou6788 2014-12-30 07:21
浏览 35
已采纳

使用预制字符串进行Laravel动态查询

How to insert strings as query in Laravel? I have to handle a dynamic value for "book formats" (such as "pdf", "epub", "physical", "") and this formats are separated by comma. Here is my code:

$formats_sql = '';
$format_filter_count = 0;
$format_filter = explode(',', $format_filter);
foreach ($format_filter as $format_filter_tmp) {
    if ($format_filter_count == 0) {
        $formats_sql .= "where('format', '=', '{$format_filter_tmp}')";
    } else {
        $formats_sql .= "->orWhere('format', '=', '{$format_filter_tmp}')";
    }
    $format_filter_count += 1;
}

if ($price_filter == 'paid') {
    $books = Book::where('book_id', '=', $category_book->book_id)->$formats_sql->where('sell_price', '>', '0')->where('status', '=', '1')->get();
}

But makes this problem:

Undefined property: Illuminate\Database\Eloquent\Builder::$where('format', '=', 'pdf')->orWhere('format', '=', 'epub') 
  • 写回答

1条回答 默认 最新

  • dpy83214 2014-12-30 07:36
    关注

    Your over complicating this. You should be using whereIn where you need to search for an array of values.

    You whole code above can be condensed to:

    if ($price_filter == 'paid') {
        $formats = explode(',', $format_filter);
        Book::where('book_id', $category_book->book_id)->whereIn('format', $formats)->where('sell_price', '>', '0')->where('status', '1')->get();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀