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


Laravel queries in route / controller / model etc

另一个问题...

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

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

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 函数进行分页时,这给了我非对象的错误。

我应该怎么做?一旦我知道一旦生病就没事了:)

谢谢!

findBuilds方法中缺少return语句:

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);
}

传统上,您可以将此逻辑放入您的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 使用刀片语法提取 $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中这样做,只需将此逻辑添加到路由中,并使用相同的刀片语法来循环你的$builds

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

(注意 - 对于具有大量路由的大型应用程序,这不是好的做法。 你的路线.php会填满,让你的生活更加艰难。如果可以,请使用控制器!