【问题标题】:how to make query on three relation with max number?如何查询与最大数量的三个关系?
【发布时间】:2021-07-06 14:17:51
【问题描述】:

我有 3 个模型

1.SellInvoice模型:

protected $table = "sell_invoices";

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

2.宝石模型:

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-03-1:

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

但它让我出错了:

语法错误或访问冲突:1055 'laravel_goldshop.jewel_items.id' 不在 GROUP BY 中(SQL:select * from jewel_items where exists (select * from sell_invoices where jewel_items.sell_invoice_id = sell_invoices.idInvoiceDate >= 2021-03-1) 分组 jewel_id)

【问题讨论】:

  • 请分享您尝试过的代码

标签: laravel eloquent laravel-query-builder


【解决方案1】:

我试试这个代码并为我工作。

$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();

【讨论】:

    【解决方案2】:
    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';
    

    【讨论】:

      猜你喜欢
      • 2010-11-20
      • 2017-01-11
      • 1970-01-01
      • 2020-11-08
      • 2019-10-28
      • 1970-01-01
      • 1970-01-01
      • 2019-08-12
      • 1970-01-01
      相关资源
      最近更新 更多