【问题标题】:Laravel dynamic queries with premade string使用预制字符串的 Laravel 动态查询
【发布时间】:2014-12-30 07:21:33
【问题描述】:

如何在 Laravel 中插入字符串作为查询?我必须处理“书籍格式”(例如“pdf”、“epub”、“物理”、“”)的动态值,并且这些格式用逗号分隔。这是我的代码:

$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();
}

但是会出现这个问题:

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

【问题讨论】:

    标签: php laravel laravel-4


    【解决方案1】:

    你把事情复杂化了。您应该使用 whereIn 来搜索值数组。

    上面的整个代码可以压缩成:

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

    【讨论】:

      猜你喜欢
      • 2019-03-08
      • 1970-01-01
      • 1970-01-01
      • 2021-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-15
      相关资源
      最近更新 更多