Laravel 如何加入一对多的关系表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48106543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:12:13  来源:igfitidea点击:

Laravel how to join one to many relationship tables

mysqllaravellaravel-5

提问by Hax0r

I am using Laravel 5.5 and I want to display list of data by joining tables that have one to many relationship.

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

Currently, I do this by going through the loop and make queries to retrieve data. This way, I think, is very inefficient, because if I were to display 1000 rows of data record, I will have to go 1000 loops to append other data with one-to-many relationship.

目前,我通过循环执行此操作并进行查询以检索数据。这种方式,我认为是非常低效的,因为如果我要显示 1000 行数据记录,我将不得不循环 1000 次以一对多关系附加其他数据。

I am thinking to get around this problem using cache but it does not seem to solve fundamental problem.

我正在考虑使用缓存来解决这个问题,但它似乎并没有解决根本问题。

For more understanding I have shared tables that I want do join as below.

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

Post Table

邮政桌

| id | comment_id | status |
|----|------------|--------|
| 1  | 1          | 0      |
| 2  | 2          | 0      |
| 3  | 3          | 1      |
| 4  | 4          | 0      |
| 5  | 5          | 1      |
| 6  | 6          | 1      |

Comment Table

评论表

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

If I were to join Table Postwith Table Comment, because they have one to many relationship, rows would not match. How would I join these two tables to show the list of post with comments?

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

Sample List 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;
}

Post Modelnamespace App\Model\Post;

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

回答by Sohel0415

Use with()for eager loading your comments.

使用with()来急切地加载您的评论。

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

So your function will be like-

所以你的功能会像-

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

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

You can filter your comments with comment_id using whereHas()like the following-

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

回答by Tommy Lee

https://laravel.com/docs/5.1/eloquent-relationships

https://laravel.com/docs/5.1/eloquent-relationships

Firstly, you may refer to this documentation.

首先,您可以参考此文档。

To setup one-to-many relationship for Post and Comment table:

为 Post 和 Comment 表设置一对多关系:

  1. A Post has Many Comments
  2. So in you Comment table there should be a column named post_id
  3. Inside your Post.php
  1. 一个帖子有很多评论
  2. 所以在你的 Comment 表中应该有一个名为 post_id 的列
  3. 在你的 Post.php 里面

public function comments()
{
    return $this->hasMany('App\Comment');
}

  1. Inside your controller
  1. 在你的控制器里面

public function list(Request $request){
    $posts = Post::where('id', 1)
                  ->with('comments')
                  ->get()

    return $posts;
}

回答by Saengdaet

public function list(Request $request, $id)

public function list(Request $request, $id)

{

{

$vaildData = $request->validate(['comment_id' => 'numeric',]);

$vaildData = $request->validate(['comment_id' => 'numeric',]);

$posts = PostModel::find($id);

return $posts->comments;

}

}

try this... Hope this can help you

试试这个...希望这可以帮助你

or you can try like this

或者你可以像这样尝试

public function list(Request $request, $id)

public function list(Request $request, $id)

{

{

$vaildData = $request->validate(['comment_id' => 'numeric',]);

$vaildData = $request->validate(['comment_id' => 'numeric',]);

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

return $posts;

}

}

回答by sysummer

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

    $posts = new PostModel;
    $results = $posts->find(1)->with('comments')//comments is the function name you defined in the App\Model\Post
    return resurts;
}

collection results contain the infomation of the post and another extra comment collection that belong to the post

收藏结果包含帖子的信息和属于该帖子的另一个额外评论集合