爲了避免查詢來重複執行一個查詢,我改變下面的代碼:使用多個操縱
首先塊
$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