Laravel在路线/控制器/模型等中查询

时间:2014-12-26 14:54:15

标签: php laravel laravel-routing

另外一个问题......

尝试深入了解如何正确执行此操作。

所以目前我的路线是这样的:

Route::get('/', function()
{
    return View::make('pages/home');
});

在那个页面中我有:

$builds = DB::table('blogs')->where('frontpage', '1')->orderBy('id', 'desc')->paginate(20);

foreach ($builds as $build) {
  // do stuff
}

这有效,但我知道不应该在视图本身中进行查询。它们应该在哪里?如何才能最好地将数据输入视图?

到目前为止,我能使其工作的唯一方法是将查询放入路径本身并压缩变量:

Route::get('/', function()
{
  $builds = DB::table('blogs')->where('frontpage', '1')->orderBy('id', 'desc')->paginate(20);
  return View::make('pages/home', compact('builds'));
});

但我相信这也不正确?

我也试过在我的模型中添加一个函数:

public static function findBuilds(){
    DB::table('blogs')->where('frontpage', '1')->orderBy('id', 'desc')->paginate(20);
}

然后在路线中:

Route::get('/', function()
{
  $builds = Blog::findBuilds();
  return View::make('pages/home', compact('builds'));
});

但是当我尝试在视图中使用我的 - > links函数进行分页时,这给了我一个非对象的错误。

我该怎么办?一旦我知道生病了就好了。)

谢谢!

2 个答案:

答案 0 :(得分:3)

您在return方法中遗漏了findBuilds声明:

public static function findBuilds()
{
    return DB::table('blogs')->where('frontpage', '1')->orderBy('id', 'desc')->paginate(20);
//  ^^^^^^ 
}

那就是说,因为你无论如何都在模型中,使用模型而不是回到DB类:

public static function findBuilds()
{
    return static::where('frontpage', '1')->latest('id')->paginate(20);
}

答案 1 :(得分:1)

传统上,您可以将此逻辑放入Controller,而不是路由.php,模型或视图中 - 对于您的情况,它可能是一个名为的控制器:PagesController

<强> /app/routes.php

// tell Laravel to route all requests to /pages/ to your PagesController
Route::controller('pages', 'PagesController');

<强> /app/controllers/PagesController.php

// now create your routes in PagesController:
class PagesController extends BaseController {

    // handles: GET pages/home
    public function getHome()
    {
        $builds = DB::table('blogs')
                    ->where('frontpage', '1')
                    ->orderBy('id', 'desc')
                    ->paginate(20);
        // pass your $builds to your view
        return View::make('pages/home')->with('builds', $builds);
    }
}    

/app/views/pages/home.blade.php 使用blade syntax提取$builds数组中每个元素的各种属性和值

@foreach($builds as $build)
// do something with the elements of your builds array
   <div class="build">
     <h2>{{ $build->name }}</h2>
     <!-- etc etc etc-->
   </div>
@endforeach

如果你正在构建一个小应用程序,这可能有点过分..所以你确实希望在你的routes.php中执行此操作,只需将此逻辑添加到路由中并使用相同的blade syntax循环你的$builds

Route::get('/', function()
{
    $builds = DB::table('blogs')->where('frontpage', '1')
                                ->orderBy('id', 'desc')
                                ->paginate(20);
    return View::make('pages/home')->with('builds', $builds);
});

(注意 - 对于较大的应用程序来说,这不是一个好的做法,有很多路由。你的routes.php会填满并让你的生活更加艰难。如果可以,请使用控制器!)

相关问题