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

时间:2014-07-09 07:28:36

标签: laravel-4

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

第一个阻止

$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

2 个答案:

答案 0 :(得分: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之间不会有任何差异。

答案 1 :(得分:0)

方法 whereSeen(0)仅适用于前10个项目,因此似乎这10个项目都不匹配该条件,这给出count = 0。

执行 $ query-&gt; get()时,在调用 - &gt; count()时已经执行了$ query。