【发布时间】:2023-03-09 06:55:02
【问题描述】:
这是一个例子,在 Laravel 中使用 Eloquent。
假设我正在开发 CMS。
- 控制器获取路由并通过路由查找页面。
- 模型提供了一个静态函数,该函数使用路由来找出它正在寻找的行的 ID
- 然后模型使用自己执行数据库查询并返回结果
示例控制器代码:
Route::get('(.*)', function($route)
{
$page = Page::load_by_route($route);
});
示例型号代码:
class Page extends Eloquent {
public static function load_by_route($route)
{
// Explode the route and trace to find the actual id of the row we need.
// ... some lines of code to accomplish it...
// Use the $id we discovered to perform the actual query
$page = Page::find($id)->first();
return $page;
}
}
在你问“为什么你不能首先使用 Page::where('route', '=', $route)->first() 之前:我是不知道“如何做”这个例子。我只是想知道在页面模型中使用 Page:: 是否不好?
【问题讨论】:
-
为什么不呢?但你可以使用
self代替类名