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

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

问题描述

我正在尝试研究是否有一种简单的方法来将可变数量的参数传递给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雄辩地搜索两个可选字段

这行得通,但在我的复杂性/模糊性方面对我来说并不陌生.

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() 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雄辩的查询,带有可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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