【问题标题】:Return random row in Laravel 4在 Laravel 4 中返回随机行
【发布时间】:2013-07-11 02:51:32
【问题描述】:

我有一个推荐表,我想在我的 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 循环并做一些类似 $row['assoc_array']

【问题讨论】:

    标签: mysql laravel laravel-4


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

    这应该提供一个名为“testimonial”的变量,您可以在视图中使用。

    【讨论】:

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

      【讨论】:

      • 好的,我没有收到任何错误,所以这似乎很好。那么,我的问题的第二部分呢?如何使用刀片循环它们并输出它们?
      • 针对不同的问题发布另一个问题
      • 认真的吗?这与我的主要问题有关。该行不是随机返回的。它的 DB 部分可能有效,但输出无效。
      猜你喜欢
      • 2015-10-09
      • 1970-01-01
      • 2016-10-27
      • 1970-01-01
      • 1970-01-01
      • 2017-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多