为了避免查询来重复执行一个查询,我改变下面的代码:使用多个操纵
首先块
$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
第一个区块$ count和第二个区块$ count有什么区别? – revo