Laravel Fluent 在不同的地方添加 select()s?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17284914/
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-09-14 08:01:20  来源:igfitidea点击:

Laravel Fluent add select()s in separate places?

mysqlselectlaravelfluenteloquent

提问by Damon

//Earlier in the code, in each Model:
query = ModelName::select('table_name.*')

//Later in the code in a function in a Trait class that is always called

    if ($column == 'group_by')
    {
        $thing_query->groupBy($value);
        $thing_query->select(DB::raw('COUNT('.$value.') as count'));
    }

Is there a way to append or include a separate select function in the eloquent query builder?

有没有办法在 eloquent 查询构建器中附加或包含单独的选择函数?

The actual ->select() is set earlier and then this function is called. I'd like to add the count column conditionally in this later function that has the query passed into it.

实际的 ->select() 更早设置,然后调用此函数。我想在稍后的函数中有条件地添加计数列,该函数将查询传递给它。

回答by Cameron

For future reference, you can use the addSelect()function.

为了将来参考,您可以使用addSelect()函数。

It would be good to have in the documentation, but you'll find it here in the API: http://laravel.com/api/4.2/Illuminate/Database/Query/Builder.html#method_addSelect

在文档中会很好,但你会在 API 中找到它:http: //laravel.com/api/4.2/Illuminate/Database/Query/Builder.html#method_addSelect

回答by Kylie

Yeah you just insert the block you wanna execute as a function....according to the documentation on Parameter Grouping, you can do like so...by passing the Where a function...

是的,您只需插入要作为函数执行的块....根据Parameter Grouping上的文档,您可以这样做...通过传递 Where a 函数...

This code below probably wont do what you want, but, its something for you to build off of, and play around with.

下面的这段代码可能不会做你想要的,但是,它是你可以构建和玩的东西。

DB::table('users')
        ->where('name', '=', 'John')
        ->orWhere(function($query)
        {
            $query->group_by($value);
                  ->select(DB::raw('COUNT('.$value.') as count'));
        })
        ->get();

回答by coffe4u

Try this:

尝试这个:

$thing_query->groupBy($value)->get(DB::raw('COUNT('.$value.') as count'));

$thing_query->groupBy($value)->get(DB::raw('COUNT('.$value.') as count'));

Also,if you are just trying to get the count and not select multiple things you can use ->count()instead of ->get()

此外,如果您只是想获得计数而不是选择多个可以使用的东西,->count()而不是->get()