SQL Laravel Eloquent 检索第一个元素并保持查询结果完整?

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

Laravel Eloquent retrieve the first element and also keep the query result intact?

sqllaravel-4eloquent

提问by Bagusflyer

Please have a look at the following code:

请看下面的代码:

$msgs = Message::where(function($query) use ($start,$end){

    $query->whereBetween('created_at', array($start, $end));

})->orderBy('created_at', 'DESC');

$first = $msgs->first()->created_at;
$ids = $msgs->lists('id');

What I'm trying to do is to get the latest date of the query result set and get all the ids from the result at the same time. But the code doesn't work because the $msgs was changed by the $msgs->first() function. I'm wondering if there is a way to let me get the first element of the query result without affecting the whole result set? Thanks

我想要做的是获取查询结果集的最新日期并同时从结果中获取所有 id。但是代码不起作用,因为 $msgs 被 $msgs->first() 函数改变了。我想知道是否有一种方法可以让我在不影响整个结果集的情况下获取查询结果的第一个元素?谢谢

回答by Jarek Tkaczyk

$first = $msgs->first(); // this does ->take(1) under the hood

Now your builder has limit = 1clause.

现在你的建造者有limit = 1条款。

So basically you need this:

所以基本上你需要这个:

// also you can use pluck:
$first = $msgs->pluck('created_at'); // returns first row`s single field
//then:
$ids = $msgs->take(9999)->lists('id'); // some high value depending on your data

Your solution is not the best, as it loads all the rows and creates objects of them, while all you need is list of ids.

您的解决方案不是最好的,因为它加载所有行并创建它们的对象,而您需要的只是 id 列表。

You can also use first()method of the Collection to fetch its first item, instead of that foreach loop:

您还可以使用first()Collection 的方法来获取它的第一项,而不是使用 foreach 循环:

$messages = $msgs->get();
$first = $msgs->first()->created_at;

回答by Bagusflyer

I found a solution:

我找到了一个解决方案:

        $msgs = Message::whereBetween('created_at', array($start, $end))                    
                            ->whereIn('advertiser_id', $array)            
                            ->orderBy('created_at', 'DESC');

        $messages = $msgs->get();
        foreach($messages as $message)
        {
            $first = $message->created_at;
            break;
        }               

Surprisingly easy. But I don't know if it's an efficient way or not.

出乎意料的轻松。但我不知道这是否是一种有效的方式。