doumeng3188 2017-08-13 02:06
浏览 79

在Laravel中合并foreach中的数据

I create function inside Model. Variable $category=1,2,3; is string

I want that function to look in table categories and to return me name of this ids in one variable to be like $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条回答 默认 最新

  • dsmlf1207915 2017-08-13 06:22
    关注

    Simply, what you want to do can be done as following.

    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;
    }
    

    However, the example above don't make use of the advantage of Model.

    Does the Model which have getCategory method have category_ids attribute?

    If it is, you can write as follows.

    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;
    }
    

    You can access category_ids which have 1,2,3 value for instance via $this so it doesn't need argument.

    To do moreover effectively, you can have category_id attribute in another model.

    In that case, you can do above more simply.

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

    评论

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本