2017-08-13 23 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

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