【问题标题】:Two table join & count second tables column in laravellaravel 中的两个表连接和计算第二个表列
【发布时间】:2021-10-13 19:48:38
【问题描述】:

我有两张表,一张是州,另一张是城市表。现在我想将状态表 state_id 与城市表 state_id 连接起来。然后我想获取带有可用城市的州表数据以及该州的数量。
NB:the query will be write with laravel query builder / eloquent
状态表:

state_id| state_name 
--------+------------
 1      | state a
 2      | state b
 3      | state c

城市表:

city_id| city_name| state_id|
-------+------------+-----------+
 1     | city a| 1|
 2     | city b| 2|
 3     | city c| 1|

【问题讨论】:

    标签: mysql laravel eloquent laravel-query-builder


    【解决方案1】:
    $data = \App\Models\State::select('states.state_id', 'states.state_name', DB::raw("count(cities.id) as city_count"))
                                                ->leftjoin('cities', function($join){
                                                    $join->on('states.state_id', '=', 'cities.state_id');
                                                })
                                                ->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-23
      相关资源
      最近更新 更多