2017-02-02 18 views
0

鑑於我有兩個foreach:第一個輸出所有類別,第二個,應該輸出目前類別的每個品牌。如何實現這樣的請求到數據庫

例子:

// Controller 
$categories = DB::table('products') 
       ->join('categories', 'products.c_id', '=', 'categories.id') 
       ->select('categories.name as cat') 
       ->groupBy('categories.name') 
       ->get(); 
$brands = DB::table('products') 
       ->join('categories', 'products.c_id', '=', 'categories.id') 
       ->join('brands', 'products.b_id', '=', 'brands.id') 
       ->select('brands.name as brand') 
       ->where('categories.id', '=', '1')<-- the problem part 
       ->groupBy('brands.name') 
       ->get(); 

//view 
@foreach($categories as $category) 
    <li><a>{{ $category->cat}}</a> 
     <ul class="sort-section"> 
      <li><a href="#"><strong>All {{$category->cat}}</strong></a></li> 
      @foreach($brands as $brand) 
       <li><a href="#">{{ $brand->brand }}</a></li> 
      @endforeach 
     </ul> 
    </li> 
@endforeach 

我不知道如何正確地輸出。現在我得到的記錄,where categories.id = 1(我做它來檢查我的代碼是否可以工作),而不是1我應該使用id當前category。換句話說,如果我想讓它發生,無論如何,我會在我的視圖中執行第一個foreach中的第二個查詢(這很瘋狂)。

有什麼建議嗎?

+0

只是所以我明白了這個問題,你想顯示的品牌列表只是與選擇相關的品牌編輯類別? – Birdman

+0

@Birdman是的,這對我來說是最難的部分:在第一個'foreach'期間,我獲得了類別的值。而對於艾維品類,我必須得到不同的品牌。這是第二個查詢中的「where」部分 – newbie

回答

1

你可以只用一個查詢呢,是這樣的:

//控制器

$getAll = DB::table('categories') 
        ->leftJoin('products', 'products.c_id', '=', 'categories.id') 
        ->leftJoin('brands', 'brands.id', '=', 'products.b_id') 
        ->groupBy('brands.name') 
        ->groupBy('categories.name') 
        ->get([ 
         'categories.id as id', 
         'categories.name as cat', 
         'brands.name as brand' 
        ]); 

     $categories = []; 
     if (count($getAll)) { 
      foreach ($getAll as $single) { 
       if (!isset($categories[$single->id])) { 
        $categories[$single->id] = new \StdClass(); 
       } 
       $categories[$single->id]->cat = $single->cat; 
       $categories[$single->id]->brands[] = $single->brand; 
      } 
     } 

然後在你看來這樣做

@foreach($categories as $category) 
<li><a>{{ $category->cat}}</a> 
    <ul class="sort-section"> 
    <li><a href="#"><strong>All {{$category->cat}}</strong></a></li> 
    @foreach($category->brands as $brand) 
     <li><a href="#">{{ $brand }}</a></li> 
    @endforeach 
    </ul> 
</li> 
@endforeach 
+0

我收到了:'未定義變量:品牌'。我試圖在控制器返回視圖('pages.index',compact(['getAll','categories']));' – newbie

+1

1.您的刀片不需要$ getAll,2.您可能會離開某處$品牌寫的,在我的例子中沒有變量名爲$品牌,只有$品牌 –

+0

Duuuudeeeee!有用。它只是因爲'blade'中的評論對Laravel不起作用而抱怨'品牌' - 刪除了我的舊評論部分,並且一切儘可能順利。非常感謝,現在我可能會在這個週末做其他事情(因爲否則我會一直在努力) – newbie

1

有兩種不同的方法可以解決這個問題。

第一種是醜陋的方式,但仍然有竅門。你可以將它分成兩個不同的部分。用戶首先選擇提交發布請求的類別,然後捕獲類別ID,然後查詢並返回與該類別關聯的品牌。這確實會強制頁面重新加載。

第二個是更乾淨的方式,它使用AJAX。使用jQuery讓一切變得簡單,這裏是一個答案,可以告訴你如何開始: Using AJAX