在Laravel中合并foreach中的数据

时间:2017-08-13 02:06:52

标签: php laravel

我在Model中创建函数。 变量$category=1,2,3;是字符串

我希望该函数查看表类别,并在一个变量中将此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;
}

2 个答案:

答案 0 :(得分: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访问1,2,3$this的{​​{1}},因此不需要argument

为了有效地做,您可以在另一个模型中拥有category_id属性。

在这种情况下,你可以更简单地做到这一点。

<强>参考: https://laravel.com/docs/5.4/eloquent-relationships#many-to-many

答案 1 :(得分:0)

无需遍历您的ID并执行多个数据库查询 - 您可以使用public function getCategory($category) { $ids = explode(",",$category); $categories = DB::table('categories')->whereIn('id',$ids)->get(); return $categories->implode('name', ','); }

只使用一个查询来获取所有这些查询
public function getCategory($category) {
    $ids = explode(",",$category);
    $categories = App\Category::find($ids);
    return $categories->implode('name', ',');
}

文档中的更多info about whereIn

然而,使用Eloquent(例如Laravel方式)来做这件事会更简洁(假设你有一个类别模型来匹配你的类别表):

.net standard library

文档中的更多info about retrieving models