在查询完成后,如何通过Collection中的where子句获取所选模型

时间:2015-10-07 04:25:51

标签: php laravel search relationship

收到收藏后,我们可以通过以下方式进行搜索:

$categories->where('name', $name)

这很简单,但是如果我们有一个多级别类别系统并且我们想要找到一个给定名称的模型,我们知道模型存在于某个地方,但我们不确定它是第一级还是更深。 / p>

我尝试

$categories->where('name', $name)->orHas('children', function() (...))

但这只能在Builder中使用,而不能在集合中使用。 所以问题是,如何通过给定的键和字段从父和子集合中检索模型,而无需再次对数据库进行排队。

当然是Laravel。

1 个答案:

答案 0 :(得分:1)

使用集合的filter方法:

$filtered = $categories->filter(function ($category) use ($name) {
    return $category->name == $name || $category->children->contains('name', $name);
});