使用两个表

时间:2017-04-11 21:04:58

标签: php laravel

我有两个表,一个用于评论,另一个用于喜欢,每行在likes表中在评论表中共享相同的注释ID,因此我可以将它们链接在一起。但是,我只是通过foreach与他们联系。

@foreach ($getNotesAll as $getnotes)

<?php
$upvoteCount = $getNoteVotes->where('noteUniqueID', $getnotes->noteUnique)-
>where('like-type', 'upvote')->count();
?>

@endforeach

使用

  $getNoteVotes =  noteLikes::all()->where('type', 'upvote');
  $getNotesAll =  Notes::orderBy('created_at','asc')->paginate(10);

我需要获得最喜欢的评论,因此我必须查询相似的表格,以降序排列具有最重复评论ID的行,然后使用类似查询中的评论标识查询评论表。在不使用foreach循环的情况下,我无法理解这一点,尽管我认为这是使用模型实现的,但任何指导都将受到赞赏

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

DB::table('commentsTable')
    ->join('likesTable', 'commentsTable.id', '=', 'likesTable.comment_id')
    ->select('commentsTable.tittle',DB::raw("count(likesTable.comment_id) as count"))
    ->groupBy('likesTable.comment_id')
    ->orderBy('likesTable.comment_id','asc')
    ->get();