Laravel条件不适用于WITH关系查询

时间:2019-10-17 11:53:02

标签: laravel eloquent

我有一个简单的查询,如下所示:

$category = Category::with('translation')
            ->with(['childCategories' => function ($query) {
                $query->active();
            }])
            ->where('id', $id)->first();

范围和关系:

public function scopeActive($query)
{
    return $query->where('active', 1);
}

public function childCategories()
{
    return $this->hasManyThrough('App\SupremeShop\Models\Category',
        'App\SupremeShop\Models\CategoryToCategory',
        'id_parent_category', //category_to_categories
        'id',  //categories
        'id',
        'id_category');  // category_to_categories.
}

因此,我正在寻找类别,给定“主要”类别的某些翻译和子类别。并且查询返回15个子类别。但是查询中的范围是只能接受活动范围,并且无法正常工作。当我使用dd时,它也会显示不活动的子类别。我试图删除范围并编写简单的WHERE,但结果是相同的。

有人认为条件不能正常工作吗?

1 个答案:

答案 0 :(得分:0)

我认为问题在于该列不明确,因为Category及其关系childCategories都是相同的模型,并且共享同一张表。

active()范围将应用于父Category而不是子Categories

尝试看看是否可行

$category = Category::from('categories as c')
                    ->with(['childCategories' => function ($query) {
                        $query->active();
                    }])
                    ->where('id', $id)->first();