2017-08-13 115 views
0

我在Model中創建函數。 可變$category=1,2,3;是字符串在Laravel中合併foreach中的數據

我想要的功能表類別看,並返回我這個ID的名稱在一個變量要像$categoryName=first,second,third

public function getCategory($category){ 
    $names = explode(",",$category); 

    foreach ($names as $name){ 
     $categories = DB::table('categories')->where('id',$name)->first(); 
     $categoryName = implode(',',(array)$categories->name); 
    } 
    return $this->$categoryName; 
} 

回答

1

簡單地說,你想要做的,可以做的事情如下所示。

public function getCategory($categoryIds) // ex) 1,2,3 
{ 

    $categoryIdArray = explode(",", $categoryIds); // [1,2,3] 
    $categoryName = ''; 
    foreach ($categoryIdArray as $categoryId){ 
     $category = DB::table('categories')->where('id',$categoryId)->first(); 
     $categoryName .= $category->name . ','; 
    } 
    $categoryName = substr($categoryName, 0, -1); 
    return $categoryName; 
} 

但是,上面的例子沒有利用Model的優點。

Model哪個有getCategory方法有category_ids屬性?

如果是這樣,你可以寫如下。

public function getCategory() 
{ 

    $categoryIdArray = explode(",", $this->category_ids); 
    $categoryName = ''; 
    foreach ($categoryIdArray as $categoryId){ 
     $category = DB::table('categories')->where('id',$categoryId)->first(); 
     $categoryName .= $category->name . ','; 
    } 
    $categoryName = substr($categoryName, 0, -1); 
    return $categoryName; 
} 

您可以訪問category_ids具有通過$this例如1,2,3值,因此它不需要argument

要有效地做到這一點,您可以在另一個模型中使用category_id屬性。

在這種情況下,你可以做得更簡單。

參考: https://laravel.com/docs/5.4/eloquent-relationships#many-to-many

+0

你解決了我的問題...非常感謝... –

+0

不客氣!我很高興問題解決了。 – Yujiro

0

無需循環在你的ID和做多的數據庫查詢 - 你可以讓他們所有,只要使用一個查詢whereIn

public function getCategory($category) { 
    $ids = explode(",",$category); 
    $categories = DB::table('categories')->whereIn('id',$ids)->get(); 
    return $categories->implode('name', ','); 
} 
在文檔

更多info about whereIn

但是這將是整潔做到這一點使用侃侃而談,在Laravel方式,例如(這裏假設你有一個分類模型,以配合您的類別表):在文檔

public function getCategory($category) { 
    $ids = explode(",",$category); 
    $categories = App\Category::find($ids); 
    return $categories->implode('name', ','); 
} 

更多info about retrieving models

+0

哎呀,我意識到你想要一個字符串返回;我最初的代碼返回了一個集合。我更新了我的答案以返回一個字符串。 –