![](/img/trans.png)
[英]How i can filter a collection with a where like query on Laravel?
[英]How I can filter a Collection in Laravel?
我有以下代碼
$tecnico = Tecnico::with('servicios')->where('Auth_Token',$auth)->firstOrFail();
if($tecnico != ''){
$servicios = $tecnico->servicios;
$servicio = $servicios->where('idServicio', $id);
}
Servicio
有許多Tecnico
和Tecnico
有很多Service
在這種情況下我只需要一個來自Auth_token
的Tecnico
以后也需要來自Tecnico
所有Servicio
但是通過id
過濾當我運行上面的代碼時出現以下錯誤
Symfony \ Component \ Debug \ Exception \ FatalErrorException
Call to undefined method Illuminate\Database\Eloquent\Collection::where()
在$servicio = $servicios->where('idServicio', $id);
我該怎么辦呢?
你可以試試這個:
$tecnico = Tecnico::with(array('servicios' => function($q) use ($id) {
$q->where('idServicio', $id);
}))->where('Auth_Token',$auth)->firstOrFail();
那么,你將得到相關的Servicio->id
等於$id
的Tecnico
模型,那么你可以使用$tecnico->servicios->first()
獲得第一個Servicio
,如果有多個Servicio
(大多數)可能不會在集合中然后你可以使用foreach
循環(基本上在view
)。 您可以在Laravel
網站上查看有關此Eager Load Constraints的Laravel
信息。
你的問題的答案是:
// 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建議的急切加載約束而不是過濾集合。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.