【问题标题】:Laravel return model with if statementLaravel 使用 if 语句返回模型
【发布时间】:2021-09-19 20:52:14
【问题描述】:

我正在尝试创建报价并将它们分配给父类别,更具体地说,我有一个报价模型,并且在报价模型中我有这么多的关系

   public function category() {
        return $this->belongsToMany(Category::class);
    }

我希望上述函数仅返回具有 NULL parent_category 的类别,这意味着它们是父类别。上面的代码可以吗?

【问题讨论】:

  • 你能显示你尝试过的查询吗
  • 检查有和没有语句

标签: php laravel eloquent


【解决方案1】:
public function category() {
    return $this->belongsToMany(Category::class)->where('parent_category', null);
}

【讨论】:

  • 虽然此代码可以回答问题,但提供有关 如何 和/或 为什么 解决问题的附加上下文将改善答案的长期价值。
【解决方案2】:

在不了解您项目的整个范围的情况下,我建议您采用以下方法之一:更改关系的名称 (A) 或保持关系原样并在需要时查询它 (B)。

选项 A -

public function childCategory() {
    return $this->belongsToMany(Category::class)->whereNull('parent_category');
}

选项 B -

public function category() {
    return $this->belongsToMany(Category::class);
}

$offer = Offer::with('category')
    ->whereHas('category' function ($query) {
        $query->whereNull('parent_category');
});

【讨论】:

    猜你喜欢
    • 2020-08-20
    • 2013-07-22
    • 2018-05-07
    • 2021-08-31
    • 2015-07-28
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 2020-09-12
    相关资源
    最近更新 更多