我使用路由绑定来确定URL的每个部分是否与前一个相关。我试图访问我的查询生成器中的路由参数/变量($ stage_number),但没有运气。为了混淆事物,如果我将变量替换为硬值,它可以工作,例如4查询生成器中无法访问的Laravel 5路由绑定变量
如何在查询中使用$ stage_number变量?
/*
* Route
*/
Route::get('/application/{application_id}/stage/{stage_number}', [
'as' => 'application.stage',
'uses' => '[email protected]'
]);
/*
* Route Service Provider
*/
// Application
$router->bind('application_id', function($application_id)
{
$application = Application::find($application_id);
if (! $application)
{
abort(404);
}
return $application;
});
// Stage
$router->bind('stage_number', function($stage_number)
{
$application = $this->getCurrentRoute()->application_id;
$stage = collect($application->stages)->where('order', $stage_number)->all();
if (! $stage)
{
abort(404);
}
return $stage;
});
更新响应patricus:
感谢有关调用集合where()
的信息;我没有意识到它对查询生成器的处理方式不同。更新我的收藏where()
完美 - 谢谢。但是,使用查询生成器时,我仍然有问题:
// Route with data
/application/1/stage/4
// Actual data returned
array:4 [▼
0 => array:2 [▼
"name" => "Information about the University or Education Course"
"order" => 3
]
1 => array:2 [▼
"name" => "Information about your education to date"
"order" => 4
]
2 => array:2 [▼
"name" => "Other Information"
"order" => 5
]
3 => array:2 [▼
"name" => "Declaration"
"order" => 6
]
]
// Desired data to be returned
array:1 [▼
0 => array:2 [▼
"name" => "Information about your education to date"
"order" => 4
]
]
无论什么样的order
我在我的路线指定我似乎得到一切返回is not null
除非我选择1
或2
(这是没有顺序排编号并从上面的数组示例中排除),然后我得到该行返回的所有其他行is not null
(如上面的示例中所示),但排除了其他任何行null
。这是由我的Application
对象上的关系引起的问题吗?
public function stages()
{
return $this->hasMany('App\Entities\Application\Stage', 'type_id')->orWhereNull('type_id')->orderBy('order', 'asc');
}
更新:
设置我的关系foreign_key
和local_key
似乎解决了其他问题:
public function stages()
{
return $this->hasMany('App\Entities\Application\Stage', 'type_id', 'type_id')->orWhereNull('type_id')->orderBy('order', 'asc');
}
感谢这样一个详细的解答。请参阅我的问题更新。 –