在一个laravel 5.5中连接两个不同的数据库
我想通过删除laravel 5.5中使用简单代码的在一个laravel 5.5中连接两个不同的数据库,laravel,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') {
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'));
}
一种方法是为您的类型创建映射,并将该类型与映射进行比较
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'));
}
编辑:我假设您希望避免
如果其他
与问题标题所说的不一样,如果我仍然不清楚,请添加评论,以便我可以更新答案谢谢
让我们在其他地方处理它,因为我猜您的函数只负责根据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;
}
我不想在这里处理它,只需发送这个函数您想要的数据的类别id。然后在其他地方用id映射类别,或者有一些函数为您提供。您需要在模型中设置连接。创建一个私有$connection变量,然后创建一个方法来设置它,再创建一个方法来获取它。然后在if/else或switch中需要时调用这些方法。如果您还没有这样做,您将需要更新第二个连接的config/database.php,然后将第二个连接添加到.env文件中。请查看以下关于设置多个数据库的内容:DownVorters请不要为添加DownVorts的评论而感到羞愧。这样,它将有助于改进答案。。谢谢:德克斯谢谢我,先生,我在公共汽车上,小姐点击了,如果你编辑它,我将删除我的否决票(实际上我不能)。我很抱歉。@aaron0207好的。但我不明白这个(事实上我不能)这意味着什么吗。。??在否决票之后我做了一个编辑。我们来这里是为了帮助某人,而不是玩投票游戏。当我试图取消否决票时,它说:“你上次对这个答案投票是在3小时前。除非这个答案被编辑,否则你的投票现在被锁定。”这就是为什么我说:“实际上我不能”。再一次,我很抱歉。祝你今天愉快