使用一个查询进行多项操作

问题描述 投票:0回答:2

为了避免重复执行查询,我更改了以下代码:

第一块

$user = Auth::user();
$user = User::find($user->id);
$notifications = $user->notifications()->take(10); // Once query runs here
$count = $user->notifications()->whereSeen(0)->count(); // there's a call for a second execution here
$total = $notifications->orderBy('created_at', 'desc')->get();

对此:

第二块

$user = Auth::user();
$user = User::find($user->id);
$query = $user->notifications()->orderBy('created_at', 'desc');
$notifications = $query->take(10);
$count = $query->whereSeen(0)->count();
$total = $query->get();

第一个输出正确,但在第二个

$count
中始终返回
int(0)
并且
$total
不会包含任何内容。出了什么问题?

更新

开始\global.php:

    $user = Auth::user();
    $user = User::find($user->id);
    $notifications = $user->notifications()->take(10); // Once query runs here
    $count = $user->notifications()->whereSeen(0)->count(); // there's a call for a second execution here
    $total = $notifications->orderBy('created_at', 'desc')->get();
    if($notifications)
    {
        $msg = array(
            'comment'   => 'A comment was posted.',
            .
            .
            .
        );

        $nots = array();
        $new = $total->each(function($not) use ($msg, &$nots)
        {
            $text = $msg[$not->type];
            $link = url('dashboard/project/view/'.$not->project_id);

            if(!in_array($not->type, array('suggest', 'comment', 'ok', 'notok', 'confirm', 'pre')))
            {
                $text = str_replace(":nick", $not->project->user->nick, $text);
            }
            $nots[] = '<a href="'.$link.'" class="item"'.($not->seen == 0 ? ' style="background-color: #EBF3EF;"' : '').'><i class="icon-signin"></i>'.$text.'<span class="time"><i class="icon-time" title="'.date('m/d', strtotime($not->created_at)).'"></i></span></a>';
        });
    }
    .
    .
    .
    View::share('notifications', $nots);

查看:

@if($notifications)
     @foreach($notifications as $not)
     {{ $not }}
     @endforeach
@endif
php laravel-4
2个回答
2
投票

让我们从这个开始:

// Assuming you use eloquent user provider
$user = Auth::user(); // 1st query for user
$user = User::find($user->id); // 2nd query for user

相反:

$user = Auth::user();

然后:

$notifications = $user->notifications()->take(10); // Once query runs here

不,事实并非如此。您的查询在此处执行(使用

count()
):

$count = $user->notifications()->whereSeen(0)->count();

现在,你的第二个代码块执行以下操作:

// $query has orderBy
$query = $user->notifications()->orderBy('created_at', 'desc');

// $query has limit(10)
$notifications = $query->take(10);

// $query has where clause
$count = $query->whereSeen(0)->count();

// $query still has all of the above
$total = $query->get();

因此,如果

count()
返回
0
,那么显然
get()
也会返回空集合。

这些代码块中的唯一区别是

whereSeen(0)
,它在第一个
get
查询中不存在。

但是,这些

count
不会有任何区别,除非您查询其他用户。


0
投票

方法 whereSeen(0) 仅适用于前 10 个项目,因此看起来这 10 个项目都不符合该条件,因此 count=0。

$query->get() 执行时,$query 在调用 ->count() 时已经执行完毕。

© www.soinside.com 2019 - 2024. All rights reserved.