php 如何在 Laravel 中构建基于条件的查询?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14179758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:48:57  来源:igfitidea点击:

How can I build a condition based query in Laravel?

phplaravel

提问by Amitav Roy

I can do this in Code Igniter:

我可以在代码点火器中做到这一点:

$this->db->select();
$this->from->('node');
if ($published == true)
{
    $this->db->where('published', 'true');
}
if (isset($year))
{
    $this->db->where('year >', $year);
}
$this->db->get();

How can this code be translated so that it works in Laravel?

如何翻译这段代码以使其在 Laravel 中工作?

回答by BenG

In Fluent you can do:

在 Fluent 中,您可以执行以下操作:

$query = DB::table('node');

if ($published == true)
    $query->where('published', '=', 1);

if (isset($year))
    $query->where('year', '>', $year);

$result = $query->get();

回答by Shawn Lindstrom

As of Laravel 5.2.27, you can avoid breaking the chain by writing your conditions as so:

Laravel 5.2.27 开始,您可以通过编写条件来避免破坏链:

$query = DB::table('node')
    ->when($published, function ($q) use ($published) {
        return $q->where('published', 1);
    })
    ->when($year, function($q) use ($year) {
        return $q->where('year', '>', $year);
    })
    ->get();

To use Eloquent,just swap $query = DB::table('node')with Node::but realize if both conditions fail, you'll get everything in the table back unless you check for some other condition before querying the db/model or from within the query itself.

要使用 Eloquent,只需交换$query = DB::table('node')Node::但要意识到如果两个条件都失败,您将恢复表中的所有内容,除非您在查询 db/model 之前或从查询本身检查其他条件。

Note the that $publishedand $yearmust be in local scope to be used by the closure.

请注意 that$published$year必须在本地范围内才能被闭包使用。

You can make it more concise and readable by creating a macro. See: Conditionally adding instructions to Laravel's query builder

您可以通过创建宏使其更加简洁和可读。请参阅:有条件地向 Laravel 的查询构建器添加指令

回答by Joel Larson

Here is how you can accomplish your query:

以下是您完成查询的方法:

$year = 2012;
$published = true;

DB::table('node')
->where(function($query) use ($published, $year)
{
    if ($published) {
        $query->where('published', 'true');
    }

    if (!empty($year) && is_numeric($year)) {
        $query->where('year', '>', $year);
    }
})
->get( array('column1','column2') );

To find more information, I recommend reading through Fluent and Eloquent in the Laravel docs. http://laravel.com/docs/database/fluent

要找到更多信息,我建议阅读 Laravel 文档中的 Fluent 和 Eloquent。 http://laravel.com/docs/database/fluent

回答by Bartando

I have not seen it here. You can even start your query like

我在这里没有看到。您甚至可以像这样开始查询

$modelQuery = Model::query();

$modelQuery = Model::query();

and then chain other query command afterwards. Maybe it will be helpful for someone new.

然后链接其他查询命令。也许这对新人会有帮助。

回答by Christian

If you need to use Eloquent you can use it like, I'm not sure that whereNotNull is the best use but I couldn't find another method to return what we really want to be an empty query instance:

如果您需要使用 Eloquent,您可以像这样使用它,我不确定 whereNotNull 是最佳用途,但我找不到另一种方法来返回我们真正想要成为空查询实例的内容:

$query = Model::whereNotNull('someColumn');
if(x < y)   
    {
        $query->where('column1', 'LIKE', '%'. $a .'%');
    }else{
        $query->where('column2', 'LIKE', '%'. $b .'%');
    }
$results = $query->get();

This way any relationships still work, for example in your view you can still use

这样任何关系仍然有效,例如在您的视图中您仍然可以使用

foreach($results as $result){
    echo $result->someRelationship()->someValue;
}

There is a good amount of info on here http://daylerees.com/codebright/eloquent-queriesabout this sort of stuff.

http://daylerees.com/codebright/eloquent-queries上有大量关于此类内容的信息。

回答by Malde Chavda

You can use Model::when()in Condition or you can create Builder::micro()

您可以Model::when()在条件中使用,也可以创建Builder::micro()

For Example

例如

$results = Model::where('user_id', Auth::id())
    ->when($request->customer_id, function($query) use ($request){
        return $query->where('customer_id', $request->customer_id);
    })
    ->get();

If You need to create micro for a condition then. follow below instruction.

如果您需要为条件创建微型,那么。按照以下说明操作。

Write thic code in your serverice provider

在您的服务提供商中编写代码

Builder::macro('if', function ($condition, $column, $operator, $value) {
    if ($condition) {
        return $this->where($column, $operator, $value);
    }

    return $this;
});

Use Like Below Example

使用如下示例

$results = Model::where('user_id', Auth::id())
    ->if($request->customer_id, 'customer_id', '=', $request->customer_id)
    ->get();

Ref: themsaid

参考:他们

回答by Adiyya Tadikamalla

We can write like this (More precise way):

我们可以这样写(更精确的方式):

$query = DB::table('node')->when($published, function ($q, $published) {
        return $q->where('published', 1);
    })->when($year, function($q, $year) {
        return $q->where('year', '>', $year);
    })->get()

Not mentioned in Laravel docs. Here is pull request.

Laravel 文档中未提及。这是拉取请求

回答by Connor Leech

In Laravel > 5.2 you can use when():

在 Laravel > 5.2 中,您可以使用when()

$results = DB::table('orders')
    ->where('branch_id', Auth::user()->branch_id)
    ->when($request->customer_id, function($query) use ($request){
        return $query->where('customer_id', $request->customer_id);
    })
    ->get();

Docs: https://laravel.com/api/5.8/Illuminate/Contracts/Container/Container.html#method_when

文档:https: //laravel.com/api/5.8/Illuminate/Contracts/Container/Container.html#method_when

Blog post: https://themsaid.com/laravel-query-conditions-20160425/

博文:https: //themsaid.com/laravel-query-conditions-20160425/

回答by Learner

for eloquent query i used following that executes only if where condition has value

对于我使用的雄辩查询,仅当条件具有值时才执行

->where(function($query) use ($value_id)
                    {

                            if ( ! is_null($value_id)) 
                                $query->where('vehicle_details.transport_type_id', $value_id);

                    })