Php 如何使用Elount或query builder连接两个表
我有一个查询,它基本上列出了两个用户共有的主题Php 如何使用Elount或query builder连接两个表,php,sql,laravel,eloquent,Php,Sql,Laravel,Eloquent,我有一个查询,它基本上列出了两个用户共有的主题 $subcommon= SubjectUser::selectRaw('topic_id, count(topic_id) AS aggregate') ->whereIn('user_id', [4, 2])->groupBy('topic_id') ->having('aggregate','>',1)->get(); 例如,下表的查询结果为 {"topic_id":3,"aggregate"
$subcommon= SubjectUser::selectRaw('topic_id, count(topic_id) AS aggregate')
->whereIn('user_id', [4, 2])->groupBy('topic_id')
->having('aggregate','>',1)->get();
例如,下表的查询结果为
{"topic_id":3,"aggregate":1}
表一
id|user_id|topic_id
1|2 |3
2|4 |3
3|5 |1
我还有另一个表(tabletwo),它也有我想要加入的topic_id,这样我就可以从第二个表中获得第2行的查询结果。我该怎么做呢
表二
id|group_id|topic_id
1|6 |2
2|7 |3
3|7 |1
试试这个
$subcommon= DB::table('tableone')
->selectRaw('topic_id, count(topic_id) AS aggregate')
->join('tabletwo','tabletwo.topic_id', '=', 'tableone.topic_id')
->whereIn('user_id', [4, 2])
->groupBy('tableone.topic_id')
->having('aggregate','>',1)
->get();
我仍然可以将
subjectuiser
模型加入到表名中,因为我似乎无法使其正常工作
$subcommon= DB::table('tableone')
->selectRaw('topic_id, count(topic_id) AS aggregate')
->join('tabletwo','tabletwo.topic_id', '=', 'tableone.topic_id')
->whereIn('user_id', [4, 2])
->groupBy('tableone.topic_id')
->having('aggregate','>',1)
->get();