Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何使用Elount或query builder连接两个表_Php_Sql_Laravel_Eloquent - Fatal编程技术网

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();