2013-07-11 48 views
0

我有一個我想在我的Laravel 4項目主頁上顯示的推薦表。通常我會運行一個查詢來獲取隨機行:在Laravel 4中返回隨機行

SELECT * FROM `testimonials` WHERE `id`=".mt_rand(1,3); 

但我得到這個錯誤試圖運行它時:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '".mt_rand(1,3)' at line 1 (SQL: SELECT * FROM `testimonials` WHERE `id`=".mt_rand(1,3);) (Bindings: array (0 => 1,)) 

這裏是我的控制器:

 public function showHome() 
{ 
      DB::select('SELECT * FROM `testimonials` WHERE `id`=".mt_rand(1,3);', array(1)); 
    return View::make('home.index', array('pageTitle' => 'Home')); 
} 

另一個問題是如何在我的home.blade.php模板中顯示這些信息?

我通常會做一個while循環,並完成類似$行[「assoc_array」]

回答

0
public function showHome() 
{ 
    DB::select('SELECT * FROM `testimonials` WHERE `id`=' . mt_rand(1, 3)); 
    return View::make('home.index', array('pageTitle' => 'Home')); 
} 
+0

好,我沒有得到任何錯誤,這樣似乎也不錯。那麼,我的問題的第二部分呢。我如何使用刀片循環並輸出它們? – Lynx

+0

認真地發佈另一個問題 –

+0

不同的問題?這與我的主要問題有關。該行不是隨機返回的。它的DB部分可能工作,但不是輸出。 – Lynx

1
$testimonial = DB::table('testimonials')->where('id', mt_rand(1, 3))->first(); 
return View::make('home.index', array('pageTitle' => 'Home', 'testimonial' => $testimonial)); 

這將提供一個名爲「見證」,您可以在您的視圖中使用的變量。