来自两个表的数据在连接时重复

时间:2014-06-11 07:59:37

标签: php mysql sql facebook laravel

我有两张桌子,我会用facebook POST作为例子。

发布表

评论表

我的查询

   $result = DB::table('posts')
            ->join('comments', 'posts.post_ID', '=', 'comments.post_ID')
            ->get();

我将收到一系列帖子和评论合并。对于现有的每条评论,他们都会有帖子数据。

我想要的是能够做类似

的事情
foreach($posts as $post){
     foreach($post['comment']{

     }
}

知道我该怎么做吗?

2 个答案:

答案 0 :(得分:0)

这样的事情应该有效:

$result = DB::table('posts')
        ->join('comments', 'posts.id', '=', 'comments.post_id')
        ->get();

在视图中:

@foreach($posts as $post)

    {{ $post->post_title }}
    {{ $post->message }}

@endforeach

确保->join('comments', 'posts.id', '=', 'comments.post_id')中的字段名称正确或相应更改。 post_title/comment_text用于演示示例,更改为原始表的字段名称,并且示例中使用{{ }}来回显数据,如果您不使用Blade然后使用echo $post->post_title代替。{/ p>

更新::

如果您使用Eloquent,请使用:

// Assumed you have defined comments as relationship method
$posts = Post::with('comments')->get(); // it's faster and called eager loading

然后在视图中:

@foreach($posts as $post)

    {{ $post->post_title }}

    @foreach($post->comments as $comment)

        {{ $comment->message }}

    @endforeach

@endforeach

答案 1 :(得分:0)

  

我将收到一系列帖子和评论合并。对于现有的每条评论,他们都会有帖子数据。

使用连接时这是正确的SQL行为。您将获得postscommentsJOIN行内的两行内容。

根据Laravel 4.2's documentation on the join method,连接函数的参数是:

join($table, $one, $operator = null, $two = null, $type = 'inner', $where = false)

使用INNER JOIN,如果您对要从中获取数据的所有帖子都有评论,那么您只会使用查询(使用内部联接)获取返回给您的行。此外,使用INNER JOIN,如果您的帖子没有评论,您将不会收到任何回复的帖子。

此外,您无法将所有评论与帖子分开,这可能意味着您正在为您发布的帖子获得结果

为您解决这个问题的简单方法是制作两个雄辩的模型:

class Post extends Eloquent {
    protected $table = 'posts';

    public function getComments() {
        return $this->hasMany('Comments', 'post_id');
    }
}

class Comments extends Eloquent {
    protected $table = 'comments';
}

您可以使用eager loading查询所有帖子:

$posts = Post::with('comments')->get();

并在你的视图中,你去:

foreach($posts as $post) {
    // echo the $post? (title, author etc)
    foreach($post->comments() as $comment) {
       // echo the $comment? (author, content etc)
    }
}
相关问题