英文:
Laravel mapping collections based on multiple conditions
问题
我有一个在我的模型上的方法,我想用它来根据多个条件返回true
/false
。
我有一组书籍,然后对它们进行映射。条件如下:
- 我不想返回附有取消日期的书籍。
- 检查流派是否为
horror
或truecrime
。
每次在测试中运行它时,似乎根据运行整个测试类还是过滤单个测试而返回不同,我无法解决。
public function hasActiveBook()
{
return $this->books->map(function ($bookMeta) {
if ($bookMeta->cancelled !== null) {
return false;
}
return in_array($bookMeta->genre, ['horror', 'truecrime']);
});
}
英文:
I have a method on my model which I want to use to return a true
/false
given multiple conditions.
I have a collection of books, I then map over them. The conditions are:
- I don't want to return a book that has a cancelled date attached to it.
- Check if the genre has either
horror
ortruecrime
.
Each time I run it in my test it seems to return different based on running the entire test class or filter the individual test and I can't work it out.
public function hasActiveBook()
{
return $this->books->map(function ($bookMeta) {
if ($bookMeta->cancelled !== null) {
return false;
}
return in_array($bookMeta->genre, ['horror', 'truecrime']);
});
}
答案1
得分: 3
利用Laravel Collection中的集合函数:
return collect($this->books)
/**
* 检查
* $bookMeta->cancelled !== null)
*/
->whereNotNull('cancelled')
/**
* 检查
* in_array($bookMeta->genre, ['horror', 'truecrime'])
*/
->whereIn('genre', ['horror', 'truecrime'])
/**
* 检查集合是否为空
*/
->isNotEmpty();
英文:
Make use of the collection functions Laravel Collection
return collect($this->books)
/**
* Checking
* $bookMeta->cancelled !== null)
*/
->whereNotNull('cancelled')
/**
* Checking
* in_array($bookMeta->genre, ['horror', 'truecrime'])
*/
->whereIn('genre', ['horror', 'truecrime'])
/**
* Checking if collection is empty or not
*/
->isNotEmpty();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论