【问题标题】:Laravel select groupby only not nullable valuesLaravel 仅选择 groupby 不可为空的值
【发布时间】:2018-10-01 18:51:23
【问题描述】:

我有一个模型产品。表格中有列 id、description、barcode、sizebarcode、price。 Sizebarcode 列有一些值和可以为空的值。我想对不可为空值的 sizebarcode 列进行分组。空值直接选择,不分组。我想在分组时省略可为空的值。

我想选择 sizebarcode 中的所有唯一值以及所有可以为空的值

控制器.php

$products = Category::where('slug',$slug)->first()->products_front()->paginate(12);

return view('page.shop',compact('products'))

模型.php

 public function products_front(){
return $this->hasMany('App\Product','cat_id','id')
    ->groupBy('sizebarcode')
    ->orderBy('created_at','asc');

}

My table

What are I want

【问题讨论】:

标签: mysql laravel


【解决方案1】:

试试这个

public function products_front(){
return $this->hasMany('App\Product','cat_id','id')
->groupBy(DB::raw('ifnull(sizebarcode,id)')
->orderBy('created_at','asc');

【讨论】:

  • @asfal c 惊人的答案...非常感谢。它解决了我的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-26
  • 2018-08-29
  • 2021-11-03
  • 1970-01-01
  • 2013-09-01
  • 1970-01-01
  • 2013-08-11
相关资源
最近更新 更多