2017-10-19 62 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'等等;所以你仍然要添加更多的步骤。顶级语法是正确的(假设关系定义正确)并且内存密集程度较低,因为没有运行额外的查询。 –