2017-08-08 138 views
0

我有两个表,即看表,然后单击表像之下Laravel连接两个表

id View_count Created_at 
1 10   January 
2 20   Febrauary 
3 30   March 

id Click_count Created_at 
1 20   January 
2 40   March 
3 30   May 

我想指望根据一个月的数据。通过查询,我想获得如下所示的表格信息。

Created_at View_count Click_count 
January   10   20 
Febrauary  20 
March   30   40 
May    30 

我试图为这样的:

$view_count= View::select(DB::raw("count(*) as count")) 
     ->orderBy("created_at") 
     ->groupBy(DB::raw("month(created_at)")) 
     ->get()->toArray(); 
    $view_count= array_column($view_count, 'count'); 

$click_count= Click::select(DB::raw("count(*) as count")) 
     ->orderBy("created_at") 
     ->groupBy(DB::raw("month(created_at)")) 
     ->get()->toArray(); 
    $click_count= array_column($click_count, 'count'); 


$count_bymonth = View::select(DB::raw('MONTHName(created_at) as month')) 
     ->groupBy(DB::raw(' MONTH(created_at)')) 
     ->get()->toArray(); 
    $count_bymonth = array_column($count_bymonth , 'month'); 


return view('testing') 
     ->with('view_count', json_encode($view_count, JSON_NUMERIC_CHECK)) 
     ->with('click_count', json_encode($click_count, JSON_NUMERIC_CHECK)) 
     ->with('count_bymonth', json_encode($count_bymonth, JSON_NUMERIC_CHECK)); 

如果有人知道这个答案请不要让我尽快知道。

谢谢。

回答

1

你可以做,在一个查询

$result = View::join('Click','Click.Created_at','=','View.Created_at') 
      ->select(
      'Click_count.Created_at' 
      DB::raw('SUM(Click_count) as Click_count'), 
      DB::raw('SUM(View_count) as View_count') 
     ) 
      ->groupBy('Click.Created_at') 
      ->orderBy("created_at") 
      ->get(); 

return view('testing')->with('result'); 

然后,所有你需要做的是循环的result

+0

我们可以得到计数的数量从两个表中具有独特的日期? – DPS

+0

你尝试过的代码?这是一个新问题吗?或者仍然与这个问题有关? –

+0

我试过先生,但无法获得预期的结果。我想从两个表中获得基于月份的数据计数 – DPS

0

使用laravel查询生成器连接

DB::table('View') 
      ->join('Click', 'View.Created_at', '=', 'Click.Created_at')->get(); 
+0

如何通过使用上面的查询按月份数据获取数据? – DPS

+0

你如何插入created_at?时间戳还是仅仅一个月? –

+0

这是一个时间戳。 – DPS