mysql - Laravel 如何连接一对多关系表

标签 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      |

评论表

| id | order_id | content  |
|----|----------|----------|
| 1  | 1        | hi       |
| 2  | 1        | hellow   |
| 3  | 1        | yes      |
| 4  | 1        | okay     |
| 5  | 2        | bye      |
| 6  | 2        | good bye |

如果我要加入表 Post 和表 Comment,因为它们是一对多的关系,所以行不会匹配。我将如何连接这两个表以显示带有评论的帖子列表?

示例列表 Controller

/**
 * @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;
}

后模型 命名空间 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');
    }
}

最佳答案

使用with()急于加载您的评论。

$posts = PostModel::with('comments')->find($id);

所以你的函数会像-

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

   $posts = PostModel::with('comments')->find(1);
   return $displayPosts;
}

您可以使用 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);

关于mysql - Laravel 如何连接一对多关系表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48106543/

相关文章:

mysql - Flutter-将列表转换为json并存储在MYSQL数据库中

php - 如何使用 DB insert 将 boolean 值 "false"插入为 0?

Laravel forge Redis 设置未定义索引 : queue on RedisConnector

Mysql查询优化

php - 为什么这个返回 bool(false)?

php - 使用 Eloquent 从 wordpress 数据库中检索用户和 usermeta 表的关系

laravel - 从 Laravel 中删除默认迁移

php - Laravel Eloquent : route model binding not working with multi word table name

PHP MySQL 搜索标题和多个标签顺序

mysql - Laravel:orderBy关系的字段