将关联结果添加到查询的地方

时间:2019-04-02 11:08:29

标签: laravel eloquent eloquent--relationship

谁能帮忙,我没主意了。

我有此代码:

$item = ItemsBrandOitb::select('ItmsGrpCod')->where('Brand', '=', $brand)->first();

return ItemsOitm::where('Country', $country)
            ->where('OnHand', '>', 0)
            ->where('ItmsGrpCod','=', $item->ItmsGrpCod)
            ->with([
               'price' => function($q) use ($country){
                  return $q->where('Country', $country);
               },
               'stock'=> function($q) use ($country){
                   return $q->where('Country', $country);
               },
               'brand' => function($q) use ($brand){
                   return $q->whereHas('Brand', '=', $brand);
               }
           ]
       )->groupBy('U_GeralRef')->orderBy('ColectionDate', 'desc')->get();

有人知道如何提出此查询:

$item = ItemsBrandOitb::select('ItmsGrpCod')->where('Brand', '=', $brand)->first();

//here:

->where('ItmsGrpCod','=', $item->ItmsGrpCod)

所以我只能有一个数据库查询?

谢谢

2 个答案:

答案 0 :(得分:0)

尝试这样的事情:

return ItemsOitm::where('Country', $country)
        ->where('OnHand', '>', 0)
        ->where('ItmsGrpCod', function ($query) use ($brand) {
            $query->from('TABLE_NAME')
                ->where('Brand', '=', $brand);
        })
        ->with([

                'price' => function( $q) use ($country){ 
                    return $q->where('Country', $country);
                },
                'stock'= > function( $q) use ($country){ 
                    return $q->where('Country', $country);
                },
                'brand' => function( $q) use ($brand){ 
                    return $q->whereHas('Brand', '=', $brand);
                }
            ]
        )->groupBy('U_GeralRef')->orderBy('ColectionDate', 'desc')->get();  

答案 1 :(得分:0)

钉它:

return ItemsOitm::where('Country', $country)
            ->where('OnHand', '>', 0)
            ->where('ItmsGrpCod', function ($query) use ($brand) {
                $query->select('ItmsGrpCod')->from('items_brand_oitbs')
                    ->where('Brand', $brand);
            })
            ->with([
                    'price' => function($q) use ($country){
                        return $q->where('Country', $country);
                    },
                    'stock'=> function($q) use ($country){
                        return $q->where('Country', $country);
                    }
                ]
            )->groupBy('U_GeralRef')->orderBy('ColectionDate', 'desc')->get();

已经删除了最后一个请求加载项(品牌),我不需要它,因为我已经在子查询中获取了值

感谢所有提供帮助的人。干杯!