【问题标题】:Store the result of an sql query to a variable (without For each) (Laravel)将 sql 查询的结果存储到变量中(没有 For each)(Laravel)
【发布时间】:2015-01-11 19:00:13
【问题描述】:

我是 Laravel 的新手,我需要你的帮助。

这在我的控制器上运行,只要我在同一个表中有 3 行具有该标题的行,结果应该是“3”。

 $countcategories = DB::table('categories')
                ->select(DB::raw('count(title) as result'))
                ->where('title','=','dsds')
                ->get();

我将查询结果传递给这样的视图->with('counts', $countcategories)

现在我的问题是:

  1. 在视图中我只能使用foreach 显示结果。为什么?我的查询只返回一行。
  2. 我想将查询结果存储在控制器内的变量中,以便使用该结果。我该怎么做?

非常感谢!

【问题讨论】:

  • 您还可以在get() 之后执行->toArray() 以获取可通过数字索引访问的模型数组。

标签: php laravel laravel-4 foreach


【解决方案1】:
  1. getting 是结果中的行,结果表明您的情况只有一个。
  2. 你已经这样做了。

无论如何,这是我的方法:

// The result
$categories = Category::where('title','=','dsds');
foreach( $categories->all() as $category ) {
    echo $category->title . "\n";
}

// The count
echo $categories->count();

【讨论】:

    【解决方案2】:

    你应该使用 ->first() 方法:

    $countcategories = DB::table('categories')
                ->select(DB::raw('count(title) as result'))
                ->where('title','=','dsds')
                ->first();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-29
      • 2012-03-13
      • 1970-01-01
      • 2014-04-24
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 2020-03-03
      相关资源
      最近更新 更多