【问题标题】:Laravel continue when relation is empty当关系为空时,Laravel 继续
【发布时间】:2019-06-04 08:24:08
【问题描述】:

我正在使用以下方法生成descriptions 的下拉列表,并将其对应的category 作为 optgroup。一个Category hasMany Descriptions

所以在这种情况下,我的activeDescriptions 是我在Category 模型中的关系。

public static function descriptions()
{
    static::active()
        ->with('activeDescriptions')
        ->orderBy('name', 'asc')
        ->get()
        ->each(function ($category) use (&$descriptions) {
            $descriptions[$category->name] = $category->activeDescriptions->pluck('name', 'id')->sortBy('name')->toArray();
        });

    return $descriptions;
}

问题是,当一个类别没有任何描述时,我想把它排除在下拉列表之外。所以我正在考虑使用类似的东西:

->each(function ($category) use (&$descriptions) {

    if($category->doesnthave('activeDescriptions'))
    {
        continue;
    }

$descriptions[$category->name] = $category->activeDescriptions->pluck('name', 'id')->sortBy('name')->toArray();

});

但这显然不起作用,但我无法弄清楚如何实现这一点。因此,任何指针将不胜感激。

【问题讨论】:

  • 顺便说一句,您在哪里生成 $descriptions 数组/集合?你引用它,但没有说从哪里来

标签: php laravel each


【解决方案1】:

您可以使用检查关系是否存在

->has('activeDescriptions')

https://laravel.com/docs/5.7/eloquent-relationships#querying-relationship-existence

【讨论】:

  • 是的,我比你早 6 分钟回答了这个问题:P 我才意识到为时已晚
【解决方案2】:

我脑海中突然出现的简单答案,我可以简单地将以下内容添加到我的查询中:

->has('activeDescriptions')

【讨论】:

  • has() 过滤查询,所以在你的情况下,如果我没记错的话,它会返回一个空集合。
【解决方案3】:

也许:

if (!$category->('activeDescriptions')->count()) {
    continue;
}

if (!count($category->('activeDescriptions')) {
    continue;
}

更新

filter 可能是更好的方法(如果在查询本身中不使用 haswhereHas):

$filtered = $categories->filter(function ($category) {
    return $category->activeDescriptions->count() === 0;
});

【讨论】:

  • 遇到同样的错误:“继续”不在“循环”或“切换”上下文中
猜你喜欢
  • 2021-12-20
  • 2015-12-25
  • 2020-02-06
  • 2014-09-23
  • 2018-09-23
  • 1970-01-01
  • 2020-07-21
  • 1970-01-01
  • 2019-06-08
相关资源
最近更新 更多