doulongsi1831 2017-03-09 12:25
浏览 53

Eloquent:现有记录的计数

I was just wondering if there's a way in laravel to return a count on how many times a record exists with eloquent?

I have two tables: cars and brands.

Cars has de fields: id, brand_id. Brands has de fields: id, name. Relationship lies on cars.brand_id = brands.id.

I have red the documents and couldn't find a solution.

Is there a way that I can how many times a brand is used by a car, so that i get the count like this:

Suzuki: 2<br>
Opel: 4 <br>
BMW: 1<br>
etc.
  • 写回答

3条回答 默认 最新

  • dongzhiji0814 2017-03-09 12:32
    关注

    You could try a query:

    SELECT count(brands.name), brands.name
    FROM cars
    JOIN brands ON cats.brand_id = brands.id
    

    Use the equivalent for Eloquent

    DB::table('cars')
    ->select(DB::raw('COUNT(brands.name), brands.name')
    ->join('brands', 'brands.id', '=', 'cars.id')
    ->groupBy('brands.name')
    ->get();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序