Laravel,如何使用groupby显示产品标题及其相关项目

时间:2019-09-10 10:46:11

标签: php laravel

对于我写问题的方式,我感到非常抱歉,我不知道该怎么解释我的问题,但希望你能得到我想要的东西;我想展示一个产品及其附加组件,一切正常,但我想将这些附加组件归类到它们的标题下,请查看屏幕截图,您可以清楚地了解我的问题 所以我想停止重复类似的标题..我对laravel非常陌生:(

image

对于桌子:我有:

   class OrderCustomize extends Model
 {
protected $table = "ordercustomizes";

protected $fillable = [

    'customizeproduct_id',
    'userorder_id',
    'product_id'
];

另一个表格:

 class CustomizeProduct extends Model
 {
protected $table = "customizeproducts";

protected $fillable = [

    'customizetitle_id',
    'product_id',
    'selection_type',
    'selection_number',
    'customize_title',
    'customize_price'
];

此表:

 class CustomizeTitle extends Model
 {
protected $table = "customizetitles";

protected $fillable = [
    'name'

];

在控制器中:

$customizeorders = OrderCustomize::where('userorder_id',$order_number)
    ->with('customizeproduct')
    ->get()
    ->groupBy('customizetitle_id');

在OrderCustomize模型中:

public function customizeproduct()
{
  return $this->belongsTo(CustomizeProduct::class);
}

在CustomizeProduct模型中:

public function customizetitle()
{
    return $this->belongsTo(CustomizeTitle::class);
}

在Blade中:

@if(count($customizeorders)>0)
    @foreach ($customizeorders as $customizetitle => $groupCustomizes)
        @foreach($groupCustomizes as $key=>$customize) 
            @if(($userorder->product_id)==($customize->product_id))

               {{$customize->customizeproduct->customizetitle->name}}:
               {{$customize->customizeproduct->customize_title}} .

            @endif
        @endforeach
    @endforeach
@endif

转储数据:

 Collection {#1554 ▼
  #items: array:1 [▼
"" => Collection {#1553 ▼
  #items: array:13 [▼    
    0 => OrderCustomize {#1485 ▶}
    1 => OrderCustomize {#1486 ▼
      #table: "ordercustomizes"
      #fillable: array:3 [▶]
      #connection: "mysql"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:6 [▼
        "id" => 45
        "customizeproduct_id" => 153
        "userorder_id" => "36-ZA"
        "product_id" => 2618
        "created_at" => "2019-09-05 01:38:47"
        "updated_at" => "2019-09-05 01:38:47"
      ]
      #original: array:6 [▶]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:1 [▶]
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [▶]
    }
  ]
}
]
}

1:https://imgur.com/w9iJHZL

1 个答案:

答案 0 :(得分:1)

您可以使用以下查询来显示标题:

$customizeorders = OrderCustomize::select( DB::raw ("GROUP_CONCAT(DISTINCT customizetitle_id) as customizetitle_ids") )
                   ->where('userorder_id',$order_number)
                   ->with('customizeproduct')->get();