模型在自身内部调用自己是不好的做法吗?

时间:2013-03-07 22:07:54

标签: php laravel eloquent

这是一个例子,在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 ::是否不好?

1 个答案:

答案 0 :(得分:6)

不,但惯例说使用self来引用当前的类:

$page = self::find($id)->first();
相关问题