2014-04-25 24 views
3

我有如下代碼如何在Laravel中過濾收藏?

$tecnico = Tecnico::with('servicios')->where('Auth_Token',$auth)->firstOrFail(); 
     if($tecnico != ''){ 
      $servicios = $tecnico->servicios; 
      $servicio = $servicios->where('idServicio', $id); 
     } 

Servicio有很多TecnicoTecnico有很多Service

在這種情況下,我只需要從Auth_token後來也Tecnico需要通過從Tecnico但過濾器的所有Servicioid當我運行上面的代碼以下錯誤

Symfony \ Component \ Debug \ Exception \ FatalErrorException 
Call to undefined method Illuminate\Database\Eloquent\Collection::where() 

$servicio = $servicios->where('idServicio', $id);

我該如何解決?

回答

3

你可以試試這個:

$tecnico = Tecnico::with(array('servicios' => function($q) use ($id) { 
    $q->where('idServicio', $id); 
}))->where('Auth_Token',$auth)->firstOrFail(); 

所以,你會得到其相關Servicio->id等於$idTecnico模式,那麼你可以使用$tecnico->servicios->first()拿到第一Servicio,如果有一個以上Servicio(最有可能不會)集合,然後你可以使用foreach循環(基本上在view)。您可以在Laravel網站上查看有關this aka Eager Load Constraints的更多信息。

+1

THX對您有所幫助,它的工作:d – cheloncio

+0

歡迎您@zhelon :-) –

3

回答你的問題可以是:

// if idServicio is set as primary key on Servicio model 
$servicio = $tecnico->servicios->find($id); 


// in case idServicio was just a property and not necessarily unique do this: 
// it return Collection of Servicio models matching $id 
$servicio = $recnico->servicios->filter(function ($servicio) use ($id) { 
    return $servicio->idServicio == $id; 
}); 

無論如何,如果你真的只需要特定的Servicio,使用預先加載的約束像@WhereWolf建議,而不是過濾收集。