Laravel 根据多个条件映射集合

huangapple go评论136阅读模式
英文:

Laravel mapping collections based on multiple conditions

问题

我有一个在我的模型上的方法,我想用它来根据多个条件返回true/false

我有一组书籍,然后对它们进行映射。条件如下:

  1. 我不想返回附有取消日期的书籍。
  2. 检查流派是否为horrortruecrime

每次在测试中运行它时,似乎根据运行整个测试类还是过滤单个测试而返回不同,我无法解决。

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:

  1. I don't want to return a book that has a cancelled date attached to it.
  2. Check if the genre has either horror or truecrime.

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();

huangapple
  • 本文由 发表于 2023年3月12日 16:34:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75711918.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定