【问题标题】:Eloquent manytomany polymorphic nested query withCount雄辩的多态多态嵌套查询 withCount
【发布时间】:2019-04-02 16:13:06
【问题描述】:

我有以下多对多态关系

资产

public function countries()
{
    return $this->morphToMany('App\Country', 'locationable');
}

国家

public function assets()
{
    return $this->morphedByMany('App\Asset', 'locationable');
}

Category 也与 Assets 有很多关系

public function assets()
    {
        return $this->belongsToMany('App\Asset', 'category_asset');
    }

我需要查询一个类别并急切加载分配了国家/地区的资产。

这是我雄辩的询问

$category = Category::with(['children.assets' => function ($query) {
            $query->whereHas('countries', function($q) {
                $q->where('code', '=', 'FR');
            });
        }])
            ->where('id', 1)
            ->first();

这似乎可行,但是当我将 Category 模型与 $this->assets 一起使用时,它会加载所有这些,即使查询中只返回一个。

我正在使用这样的 API 资源

AssetResource::collection($this->whenLoaded('assets'))

我在哪里可以设置仅使用通过条件 where('code', '=', 'FR') 的资产的条件

【问题讨论】:

  • 请添加children 关系。你到底在哪里使用$this->assets

标签: laravel-5 eloquent laravel-5.7


【解决方案1】:

这是我的错误,我应该像这样检查儿童类别:

Category::with(
                ['children' => function ($query) {
                $query->with(['children.assets' => function ($q) {
                    $q->country('GB');
                }]);
            }])
                ->where('id', 1)
                ->first();

类别有子类别

public function children()
    {
        return $this->belongsToMany('App\Category', 'parent_category_child_category', 'parent_category_id', 'child_category_id');
    }

【讨论】:

    猜你喜欢
    • 2020-01-14
    • 2014-10-08
    • 2020-03-11
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    • 2020-11-16
    • 2021-05-29
    • 1970-01-01
    相关资源
    最近更新 更多