【问题标题】:How To Use groupBy in whereHas laravel如何在 whereHas laravel 中使用 groupBy
【发布时间】:2020-04-26 11:46:53
【问题描述】:

我在我的项目中使用Metable 为订单创建元
但我有一个问题
我想要具有相同电子邮件的团体订单
这是表图片:image 1image 2

我需要这样的代码才能工作:)

Order::whereHas( 'meta', function($query) {
        $query->where("key" , "gmail");
})->groupBy('meta.value')->get();

这是在订单模型中由 trait 'use Metatable' 调用的元关系:

public function meta(): MorphMany
{
    return $this->morphMany($this->getMetaClassName(), 'metable');
}

谢谢

【问题讨论】:

    标签: laravel meta wherehas


    【解决方案1】:

    这个查询可能有效,我们从元模型开始查询:

    Meta::with('metable')
        ->whereHasMorph('metable', Order::class)
        ->where('key', 'gmail')
        ->get()
        ->groupBy('value')
        ->map(function ($metaCollection) {
            return $metaCollection->map->metable->unique('id');
        });
    

    【讨论】:

    • 它不起作用 :( | 表示此集合实例上不存在属性 [值]。
    • 您能否发布一张显示所有列名的元表的不同图像?
    • 我知道它为什么失败并相应地更新了答案,请检查。
    • tnx 伙计,它的工作:) 反正有从 Order 而不是 Meta?
    【解决方案2】:

    这是未经测试的,但我会尝试从 Order 类中检索模型:

    Order::whereHas('meta', function($query) {
        $query->where('key', 'gmail');
    })->with(['meta' => function($query) {
        $query->groupBy('value')
    }])->get();
    

    【讨论】:

    • 不工作,此代码返回所有具有元的对象!和 groupby 不工作
    【解决方案3】:

    试试这个解决方案:

    Order::whereHas( 'meta', function($query) {
        $query->where("key" , "gmail")
        $query->groupBy('meta.value');
    })->get();
    

    【讨论】:

      猜你喜欢
      • 2018-09-17
      • 1970-01-01
      • 2017-09-17
      • 1970-01-01
      • 2023-03-07
      • 2020-08-27
      • 2022-10-12
      • 1970-01-01
      • 2017-09-21
      相关资源
      最近更新 更多