雄辩的laravel:如何从 - > get()获取行数

时间:2015-11-12 16:34:57

标签: php sql laravel eloquent

我在弄清楚如何使用此集合计算行时遇到了很多麻烦。

$wordlist = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
                ->get();

我尝试了adding->count(),但没有成功。我尝试过做count($wordlist)。如果不需要第二个请求作为a->count()方法,我真的不确定该做什么。

4 个答案:

答案 0 :(得分:35)

答案已更新

count是一种Collection方法。查询构建器返回一个数组。因此,为了得到计数,你只需像通常使用数组一样计算:

$wordCount = count($wordlist);

如果您有wordlist模型,那么您可以使用Eloquent获取Collection,然后使用Collection的count方法。例如:

$wordlist = Wordlist::where('id', '<=', $correctedComparisons)->get();
$wordCount = $wordlist->count();

有关于让查询构建器在此处返回集合的讨论:https://github.com/laravel/framework/issues/10478

但是截至目前,查询构建器始终返回一个数组。

编辑:如上所述,查询构建器现在返回一个集合(不是数组)。因此,JP福斯特最初尝试做的事情将起作用:

$wordlist = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
            ->get();
$wordCount = $wordlist->count();

然而,正如Leon在评论中指出的那样,如果您想要的只是计数,那么直接查询它比获取整个集合然后获得计数要快得多。换句话说,你可以这样做:

// Query builder
$wordCount = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
            ->count();

// Eloquent
$wordCount = Wordlist::where('id', '<=', $correctedComparisons)->count();

答案 1 :(得分:16)

< Products Table >
Column Z  Column X Column Y
Product 1 Price 1  Delivery A
Product 2 Price 2  Delivery B
Product 3 Price 3  Delivery A
Product 4 Price 4  Delivery A
Product 5 Price 5  Delivery B
Product 6 Price 6  Delivery C

< Delivery Table >
Column O  Column P
Delivery A Warehouse A
Delivery B Warehouse A
Delivery C Warehouse B

< Warehouse Percentage Table >
Column M Column N
Warehouse A  Percentage A
Warehouse B  Percentage B

< Results Table / View >
Column E  Column F
Product 1 Total 1 (Price 1 * Percentage A)
Product 2 Total 2 (Price 2 * Percentage B
Product 3 Total 3 (Price 3 * Percentage A)
Product 4 Total 4 (Price 4 * Percentage A)
Product 5 Total 5 (Price 5 * Percentage B)
Product 6 Total 6 (Price 6 * Percentage B)

答案 2 :(得分:7)

最好使用laravels count方法访问计数

$count = Model::where('status','=','1')->count();

$count = Model::count();

答案 3 :(得分:2)

此外,您可以获取所有数据并在刀片文件中计数。 例如:

您在控制器中的代码

class FormA
{
     // apparently FormA knows about FormB:
     private FormB { get => ...}

     private void ShowButtonOnFormB()
     {
          // maybe some code to make sure FormB is shown
          this.FormB.MakeMyButtonVisible();
     }

     private void OnMenuItem_ShowMyButton_Clicked(object sender, ...)
     {
          this.ShowBuffonFormB();
     }
}

您在刀片文件中的代码。

$posts = Post::all();
return view('post', compact('posts'));

最后,您可以看到自己的帖子总数。