Laravel如何连接一对多关系表

New*_*_TT 1 mysql laravel laravel-5

我正在使用Laravel 5.5,我想通过加入具有一对多关系的表来显示数据列表。

目前,我是通过遍历循环并进行查询以检索数据来实现的。我认为这种方式效率很低,因为如果我要显示1000行数据记录,则必须经过1000次循环才能以一对多关系附加其他数据。

我正在考虑使用缓存来解决此问题,但它似乎无法解决基本问题。

为了获得更多的理解,我共享了一些想要加入的表,如下所示。

发布表

| id | comment_id | status |
|----|------------|--------|
| 1  | 1          | 0      |
| 2  | 2          | 0      |
| 3  | 3          | 1      |
| 4  | 4          | 0      |
| 5  | 5          | 1      |
| 6  | 6          | 1      |
Run Code Online (Sandbox Code Playgroud)

评论表

| id | order_id | content  |
|----|----------|----------|
| 1  | 1        | hi       |
| 2  | 1        | hellow   |
| 3  | 1        | yes      |
| 4  | 1        | okay     |
| 5  | 2        | bye      |
| 6  | 2        | good bye |
Run Code Online (Sandbox Code Playgroud)

如果我将Table Post与Table 联接在一起Comment,因为它们之间存在一对多的关系,那么行将不匹配。我将如何结合这两个表格来显示带有评论的帖子列表?

样品清单控制器

/**
 * @param Request $request
 * @return \Illuminate\Http\JsonResponse
 */
public function list(Request $request)
{
    $vaildData = $request->validate([
        'comment_id' => 'numeric',
    ]);

    $posts = new PostModel;
    $posts->find(1);
    $displayPosts = [];

    foreach ( $posts->find(1)->get() as $post ) {
        $displayPosts->comments = $post->comment()->get();
    }

    return $displayPosts;
}
Run Code Online (Sandbox Code Playgroud)

发布模型 名称空间App \ Model \ Post;

use SoftDeletes;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function comments()
    {
        return $this->hasMany('App\Model\Post\Comment’, ‘post_id', 'id');
    }
}
Run Code Online (Sandbox Code Playgroud)

Soh*_*415 5

与with()一起使用以加载您的评论。

$posts = PostModel::with('comments')->find($id);
Run Code Online (Sandbox Code Playgroud)

所以,你的功能将喜欢 -

public function list(Request $request)
{
   $vaildData = $request->validate([
    'comment_id' => 'numeric',
   ]);

   $posts = PostModel::with('comments')->find(1);
   return $displayPosts;
}
Run Code Online (Sandbox Code Playgroud)

您可以使用whereHas()使用comment_id过滤评论,如下所示:

$comment_id = $request->input('comment_id');
$posts = PostModel::with('comments')->whereHas('comments', function ($query) use($comment_id)
      {
        $query->where('id', '=', $comment_id);
      })->find(1);
Run Code Online (Sandbox Code Playgroud)