在一个laravel 5.5中连接两个不同的数据库

时间:2017-10-19 05:12:52

标签: laravel

我希望通过使用laravel 5.5中的简单代码删除if else语句来最小化这种情况。有人可以帮助我吗?

public function shirts($type='')
{
    if($type == 'glass') {
        $shirt = Product::where('category_id','1')->get();
        $products = Category::find(1);
    } elseif ($type == 'ic') {
        $shirt = Product::where('category_id','2')->get(); 
        $products = Category::find(2);
    } elseif ($type == 'cover') {
        $shirt = Product::where('category_id','3')->get();
        $products = Category::findOrFail(3);
    } else {
        $shirt = Product::all();
    }
    return view('front.shirt',compact('products','shirt'));
}

2 个答案:

答案 0 :(得分:0)

一种方法是为您的类型创建映射并将类型与映射进行比较。

public function shirts($type = '')
{
    $type_mappings = [
        'glass' => 1,
        'ic'    => 2,
        'cover' => 3
    ];

    if(array_key_exists($type, $type_mappings)) {
        $shirt = Product::where('category_id', $type_mappings[$type])->get();
        $products = Category::find($type_mappings[$type]);
    } else {
        $shirt = Product::all();
        $products = null;
    }

    return view('front.shirt', compact('products', 'shirt'));
}

答案 1 :(得分:0)

编辑我认为你想避免if else不是问题标题所说的如果我还不清楚请添加评论以便我可以更新答案谢谢!

让我们在其他地方处理它,因为我猜你的函数只有责任找到基于id的产品,它没有映射部分所以我们可以有类似的东西:

// Your function with single responsibility to return product.
public function shirts($category = '')
{
    $type = $this->CategoryIdMapper($category);

    if($type == 0) {
        $shirt = Product::all();
        $products = null;
    } else{
        $shirt = Product::where('category_id',$type_id)->get(); 
        $products = Category::findOrFail($type_id); 
    }
    return view('front.shirt',compact('products','shirt'));
}

//let the mapping part be done by some independent function which you can later modify accordingly and independently.
public function CategoryIdMapper($category)
{
   $categories = ['glass'=>1, 'ic'=> 2, 'cover' => 3 ];
   if(array_key_exist($category,$categories))
   {
      return $categories[$category];
   }
   return 0;
}
相关问题