好的,所以我以前有这段代码,它可以正常工作:
$lastpost = ForumPos::where('user_id', '=', Auth::id())->orderby('created_at', 'desc')->first();
if ($validator->fails())
{
return Redirect::to('/forum/topic/'.$id.'/new')
->withErrors($validator->messages());
}
elseif ($lastpost->created_at->diffInSeconds() < 15)
{
return Redirect::to('/forum/topic/'.$id.'/new')
->withErrors('You really need to slow down with your posting ;)');
}
else
{
$new_thread = new ForumThr;
$new_thread->topic = $id;
$new_thread->user_id = Auth::id();
$new_thread->title = Input::get('title');
$new_thread->save();
$new_post = new ForumPos;
$new_post->thread = $new_thread->id;
$new_post->user_id = Auth::id();
$new_post->body = Input::get('body');
$new_post->save();
return Redirect::to('/forum/thread/'.$new_thread->id.'');
}
一切正常,直到我注意到一个小问题,所以我不得不对此稍作改动以获取此信息:
$hasposted = ForumPos::where('user_id', '=', Auth::id())->count();
if ($validator->fails()){
return Redirect::to('/forum/topic/'.$id.'/new')
->withErrors($validator->messages());
} elseif ($hasposted != 0) {
$last_post = ForumPos::where('user_id', '=', Auth::id())->orderBy('created_at', 'DESC')->first();
if ($last_post->created_at->diffInSeconds() < 15) {
return Redirect::to('/forum/topic/'.$id.'/new')
->withErrors('You really need to slow down with your posting ;)');
}
} else {
$new_thread = new ForumThr;
$new_thread->topic = $id;
$new_thread->user_id = Auth::id();
$new_thread->title = Input::get('title');
$new_thread->save();
$new_post = new ForumPos;
$new_post->thread = $new_thread->id;
$new_post->user_id = Auth::id();
$new_post->body = Input::get('body');
$new_post->save();
return Redirect::to('/forum/thread/'.$new_thread->id.'');
}
现在,当我发布一个线程并进入elseif语句中的if语句时,我遇到了一个障碍。我收到以下错误:
仅当我未在控制器中指定title变量时才出现此错误,因此视图可以获取它,但是不应有一个视图。有任何想法吗?:S
看看您的elseif
障碍物(第二种情况)
if(...)
{
//first condition
return ...;
}
elseif ($hasposted != 0) {
{
//second condition
$last_post = ForumPos::where('user_id', '=', Auth::id())->orderBy('created_at', 'DESC')->first();
if ($last_post->created_at->diffInSeconds() < 15) {
return Redirect::to('/forum/topic/'.$id.'/new')
->withErrors('You really need to slow down with your posting ;)');
}
}
else
{
//third condition
return ...;
}
当您的嵌套if语句失败时
$last_post->created_at->diffInSeconds() < 15
此块完成,其余条件条件完成,而不发出Redirect
。也就是说,您的嵌套if语句对第三个条件一无所知。PHP / Laravel正在执行您要求的操作-因此,请告诉它执行其他操作。
这纯粹是一种样式建议,但我已经达到了避免可能的多个分支条件的地步,尤其是从分支内部返回时。风格更像
if(...)
{
return Redirect(); //...
}
if(...)
{
return Redirect(); //...
}
if(...)
{
return Redirect(); //...
}
if(...)
{
return Redirect(); //...
}
可能会在页面上看起来更长,但更清楚了发生了什么。
If this? Do something and go away (`return`)
Still here? Well if this-other-thing then do something and go away (`return`)
**Still** here? Well if this-other-thing then do something and go away (`return`)
您最终会思考一系列的是/否测试,并避免了嵌套条件逻辑遇到的非常人为/程序员的问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句