Php 在Laravel中返回一个有口才的对象
我有这个功能:Php 在Laravel中返回一个有口才的对象,php,laravel,eloquent,Php,Laravel,Eloquent,我有这个功能: protected function compare_something($found_item, $saved_items) { foreach($saved_items as item) { $compare_x = false; $compare_y = false; $compare_z = false; $compare_x = strpos($found_item,$item->x) !== false ? true: false; $compare_y =
protected function compare_something($found_item, $saved_items)
{
foreach($saved_items as item) {
$compare_x = false;
$compare_y = false;
$compare_z = false;
$compare_x = strpos($found_item,$item->x) !== false ? true: false;
$compare_y = strpos($found_item,$item->y) !== false ? true: false;
$compare_z = strpos($found_item,$item->z) !== false ? true: false;
if($compare_x && $compare_y && $compare_z){
return $item;
}
}
return false;
}
我希望$item
是对象,其中$compare\u x、
和$compare\u z
为真,但是此函数只返回整个有说服力的对象($saved\u items
),而不是比较的对象
我不知道为什么会这样。我可以随时返回:
$item->id
然后执行Item::where(“id”,$Item->id)->first()代码>
但是不应该只返回$item
只给我所选的项目吗?雄辩的查询总是返回一个集合,因此您可以轻松地使用此函数。然后调用函数以获取第一个元素。如果集合中没有元素,将返回null
例如:
return $saved_items->filter(function ($item) use ($found_item) {
return strpos($found_item, $item->x) !== false &&
strpos($found_item, $item->y) !== false &&
strpos($found_item, $item->z) !== false;
})->first();
雄辩的查询总是返回一个集合,因此您可以轻松地为此使用该函数。然后调用函数以获取第一个元素。如果集合中没有元素,将返回null
例如:
return $saved_items->filter(function ($item) use ($found_item) {
return strpos($found_item, $item->x) !== false &&
strpos($found_item, $item->y) !== false &&
strpos($found_item, $item->z) !== false;
})->first();
作为旁注,如果您有一个雄辩
项目列表,它们将存储为集合
,该集合有一个方便的过滤器()
函数:(注意根据您的Laravel版本有一些语法变化)。作为旁注,如果您有一个雄辩
项目列表,它们将存储为集合
,它有一个方便的filter()
函数:(请注意,根据您的Laravel版本,语法有一些细微的变化)。或者,如果您将first()
与相同的函数(而不是filter()
)一起使用,您会得到相同的结果。()或者,如果将first()
与相同的函数一起使用(而不是filter()
),您将得到相同的结果。()