如何使用eloquent或查询构建器连接两个表

时间:2015-05-31 07:37:00

标签: 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":1} 

tableone

id|user_id|topic_id
 1|2      |3
 2|4      |3
 3|5      |1

我有另一个表(tabletwo)也有topic_id,我想加入,以便从第二个表中获取第2行的查询结果。我该怎么做呢?

tabletwo

id|group_id|topic_id
 1|6      |2
 2|7      |3
 3|7      |1

2 个答案:

答案 0 :(得分:0)

        curr = n;
        pos = 0;
        ans[pos] = n;
        while(pre[curr] != -1) {
            pos++;
            ans[pos] = pre[curr];
            curr = pre[curr];
        }
        for(int i=pos;i>=0;i--) { // reverse order to output
            System.out.println(ans[i]);
        }

答案 1 :(得分:0)

试试这个,

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