2017-02-22 42 views
0

記錄如何組基於相似的ID在Laravel 例如表中的記錄: 在MySQL產品表有類似貓ID 表名folllowing記錄:產品Laravel - 組基於相似的ID在Laravel

id:1 pro_name:xyz1 cat_id:55 
id:2 pro_name:xyz2 cat_id:22 
id:3 pro_name:xyz3 cat_id:55 
id:4 pro_name:xyz4 cat_id:22 

我想要做的是類似的cat_id它應該使其數組。我嘗試使用

$all = Products::groupBy('cat_id')->get(); 

但它只顯示每個類似cat_id的第一條記錄。

輸出我得到:

{ 
    "id": 1, 
    "pro_name": "xyz1", 
    "cat": "55", 
    "created_at": "2017-02-09 13:09:13", 
    "updated_at": "2017-02-18 11:56:04" 
    }, 
    { 
    "id": 2, 
    "pro_name": "xyz2", 
    "cat": "22", 
    "created_at": "2017-02-22 06:04:23", 
    "updated_at": "2017-02-22 06:04:23" 
    } 

我想它應該顯示類似ID的所有記錄在一個陣列 幫我這個

+0

你能分享所需的結果嗎? – DevOps

+0

可以使用GROUP_CONCAT,但要獲取相同的數組,您需要運行單獨的查詢。 – DevOps

回答

1

集團通過總結你的表,使用給定的參數(因此它只顯示第一個參數,而在奈尼的答案中,總計是爲分組元素計算的)。

也許您在尋找Order By?

$info = DB::table('Products') 
    ->orderBy('cat_id') 
    ->get(); 

你會得到整個表,由cat_id排序的結果,也就有了在一個類別手動變化來檢測。

另一種方法是獲取不同的cat_id,然後在它們上運行自己的查詢。您可以將代碼封裝在模型或存儲庫中。請注意,這將在您的數據庫上運行一些查詢,這可能不是更可取的。

//Create an array 
$groups = [] 

//Retrieve the list of cat_id's in use. 
$cats = DB::table('Products')->distinct()->select('cat_id')->get() 

//for each cat_id in use, find the products associated and then add a collection of those products to the relevant array element 
foreach($cats as $cat){ 
    $groups[$cat->cat_id] = DB::table('Products')->where('cat_id', $cat->cat_id)->get(); 
} 

注意:我唯一關心的是你在這裏做的是你真的在尋找關係嗎?如果你使用Eloquent,所有這些變得非常簡單。

0

可以試試這個

$info = DB::table('Products') 
     ->select('cat_id', DB::raw('count(*) as total'), 
      DB::raw("GROUP_CONCAT(pro_name) AS product_name")) 
     ->groupBy('cat_id') 
     ->get(); 
+0

它示出了作爲'{ 「CAT_ID」: 「22」, 「總」: 「2」 }輸出, { 「CAT_ID」: 「55」, 「總」: 「2」 },' @Naincy – Mohammed

+0

是的,它表明,對於cat_id你有2條記錄和55也有2條記錄 – Naincy

+0

但我希望所有的領域不是全部。 @Naincy – Mohammed

0

嗨你應該試試這個代碼...

$行=產品:: selectRaw( 「pro_name,CAT_ID」) - > GROUPBY( 「CAT_ID」, 「pro_name」) - >獲得();

  echo "<pre>"; 
      print_r($row);