如何查询最大数量的三个关系?

how to make query on three relation with max number?

我有3个模型

1.SellInvoice 型号:

protected $table = "sell_invoices";

public function jewelsItems(){
  return $this->hasMany(JewelsItem::class,'buy_invoice_id');
}

2.Jewel 型号:

protected $table = 'jewel';

public function jewelsItems(){
return $this->hasMany('App\Models\JewelsItem');
}

3.JewelsItem 型号:

protected $table = 'jewel_items';

public function jewel(){
  return $this->belongsTo('App\Models\Jewel');
}

public function sellInvoice(){
    return $this->belongsTo(SellInvoice::class,'sell_invoice_id');
}

查询: 在我的数据库中找到 10 个最畅销的珠宝,或者根据某个日期的销售数量对结果进行排序。

注意: 我在 SellInvoice 中有一个 InvoiceDate 并且必须使用它来了解哪个珠宝在某个日期最畅销

尝试:我尝试通过打折商品获取群组,从 2021 年 3 月 1 日开始打折:

JewelsItem::whereHas('sellInvoice',function ( $query) {
        $query->where('InvoiceDate','>=','2021-03-1');
    })->groupby('jewel_id')->get();

但它让我出错:

Syntax error or access violation: 1055 'laravel_goldshop.jewel_items.id' isn't in GROUP BY (SQL: select * from jewel_items where exists (select * from sell_invoices where jewel_items.sell_invoice_id = sell_invoices.id and InvoiceDate >= 2021-03-1) group by jewel_id)

set global 
sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';

我尝试使用此代码并为我工作。

$jewel = Jewel::whereHas('jewelsItems', function (Builder $query) {
        $query->whereNull('sell_invoice_id');
    })->withCount(['jewelsItems'=> function (Builder $query) use ($date) {
        $query->whereIn('sell_invoice_id',SellInvoice::select('id')->where('InvoiceDate','>=',$date));
    }])->orderBy('jewels_items_count','desc')->get();