2014-04-25 28 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建议,而不是过滤收集。