2017-10-19 52 views
0

我正在循環收集並訪問模型上屬性,以便收集項目的用戶。Laravel - 獲取集合中每個集合的最新模型屬性

$advancedBookingsQuery = Booking::query(); 
$advancedBookingsQuery = $advancedBookingsQuery->where('type', 2) 
    ->with('staffMember.user'); 
$advancedBookings = $advancedBookingsQuery->get(['id', 'requested_booking_time', 'estimated_booking_time']); 

foreach ($advancedBookings as $booking) { 
    $barberQueueLength = $booking->staffMember->user->currentQueueLength; 
    $booking->update(['estimated_booking_time' => Carbon::now()->addMinutes($barberQueueLength)]); 
} 

currentQueueLength方法運行一些查詢以獲得符合要求的總預訂的長度。

public function getCurrentQueueLengthAttribute() 
{ 
    // Calc length of all bookings with an estimated booking time value 
} 

問題是currentQueueLength屬性總是返回集合中每個項目的相同值。

有沒有一種方法可以在集合的每次迭代中新調用該屬性 - >每種方法?它似乎只是在收集$ advancedBookings集合時使用該值。

+0

每[Laravel訪問者&增變器(https://laravel.com/docs/5.5/eloquent-mutators#accessors -and-mutators),current_ueueLength是不是'current_queue_length'? – ljubadr

回答

0

我昨天碰到了類似的問題,而不是使用

$booking->staffMember->user->currentQueueLength; 

嘗試使用

$booking->staffMember()->first()->user()->first()->currentQueueLength; 

也可以嘗試尋找到的刷新方法:https://laravel.com/api/5.5/Illuminate/Database/Eloquent/Model.html#method_refresh 我沒有親自嘗試過,因爲第一個解決方案解決了我的問題

+1

' - > get()'返回'Collection',所以''> get() - > user()'會嘗試訪問不存在的'Collection'函數'User'。 –

+0

我的不好,應該先用,用修正編輯答案 –

+1

這很好,但' - > staffMember'(沒有括號)會返回' - > first()'或' - > get()取決於關係是否被包含爲' - > with()'子句,並基於'hasOne','belongsTo'等等;所以你仍然要添加更多的步驟。頂級語法是正確的(假設關係定義正確)並且內存密集程度較低,因爲沒有運行額外的查詢。 –