带有可选参数的 Laravel Eloquent 查询 [英] Laravel Eloquent query with optional parameters

查看:31
本文介绍了带有可选参数的 Laravel Eloquent 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解是否有一种简单的方法可以将可变数量的参数传递给 Eloquent 中的查询,希望使用 array.

I am trying to learn whether or not there is a simple way to pass a variable number of parameters to a query in Eloquent, hopefully using an array.

据我所知,如果不循环遍历 Input 以查看请求中设置的内容,似乎没有办法做到这一点.

From what I can find, there doesn't seem to be a way to do this without looping through the Input to see what was set in the request.

示例:Laravel Eloquent 搜索两个可选字段

这行得通,但我觉得它的复杂性/不优雅让我感觉不像 Laravel.

This would work, but feels non-Laravel to me in its complexity/inelegance.

这就是我所在的地方,这可能是不可能的,只是希望其他人解决了类似的问题:

Here is where I am, and this may not be possible, just hoping someone else has solved a similar issue:

$where = array("user_id" => 123, "status" => 0, "something else" => "some value");

        $orders = Order::where($where)->get()->toArray();
        return Response::json(array(
                'orders' => $orders
                ),
            200
        );

这当然会返回一个错误strtolower() 期望参数 1 是字符串,给定的数组.

That returns an error of course strtolower() expects parameter 1 to be string, array given.

这可能吗?

推荐答案

Order::where 实际上返回一个查询构建器的实例,所以这可能比你想象的要容易.如果您只想获取查询构建器的该实例并一次构建"一个 where() 查询,您可以像这样得到它:

Order::where actually returns an instance of query builder, so this is probably easier than you thought. If you just want to grab that instance of query builder and "build" your query one where() at a time you can get it like this:

$qb = (new Order)->newQuery();
foreach ($searchParams as $k => $v) {
    $qb->where($k, $v);
}
return $qb->get(); // <-- fetch your results

如果您想查看查询构建器正在做什么,您也可以执行该 get() 并在不久之后执行:

If you ever want to see what query builder is doing you can also execute that get() and shortly after:

dd(DB::getQueryLog());

这将显示结果查询的样子;这在使用 Eloquent 时非常有用.

That will show you what the resulting query looks like; this can be very useful when playing with Eloquent.

这篇关于带有可选参数的 Laravel Eloquent 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆