2017-10-19 107 views
-2

我想通过使用laravel 5.5中的简单代码删除if else语句来尽量减少这种情况。有人可以帮助我吗?在一个laravel中连接两个不同的数据库5.5

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')); 
} 
+0

http://php.net/ manual/en/control-structures.switch.php –

+0

我宁愿不在这里处理它,只是发送这个函数的类别ID为你想要的数据..和其他地方类别与ID或具有一些功能,它会为你。 – RohitS

+0

您需要在模型中设置连接。创建一个私有的$连接变量,然后设置一个方法来获取它。然后在if/else或switch中需要时调用这些方法。如果你还没有这样做,你将需要更新你的config/database.php作为第二个连接,然后将第二个连接添加到你的.env文件 – developernator

回答

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')); 
} 
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; 
} 
+0

Downvoters请不要为添加评论而感到羞耻..因此,它将有助于改善答案。谢谢:D – RohitS

+0

对不起,先生,我在公车上,想念点击,如果你编辑它,我会删除我的downvote(实际上我不能)。对不起。 – aaron0207

+0

@ aaron0207好吧..但我没有得到这个(实际上我不能)这是否意味着什么..?我在downvote后做了一个编辑..我们在这里帮助某人不玩一些投票游戏.. – RohitS

相关问题