Laravel 批量显示关系数据

Laravel 批量显示关系数据,laravel,laravel-7,Laravel,Laravel 7,我正在写一个API,这里有我的主题和与之相关的评论。我的愿望是显示所有主题,同时也显示属于主题的评论。我与hasMany选项建立了关系,但显示数据时遇到问题 Post表 评论表 后期模型 <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Posts extends Model { protected $table = 'posts'; protected $f

我正在写一个API,这里有我的主题和与之相关的评论。我的愿望是显示所有主题,同时也显示属于主题的评论。我与hasMany选项建立了关系,但显示数据时遇到问题

Post表

评论表

后期模型

    <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Posts extends Model
{
    protected $table = 'posts';
    protected $fillable = [
        'post_id',
        'user_id'
    ];

    public function user(){
        return $this->belongsTo('App\Models\Users');
    }

    public function comment()
    {
        return $this->hasMany('App\Models\Comments', 'post_id', 'id');
    }
}
    <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Comments extends Model
{
    protected $fillable = [
        'user_id',
        'post_id',
        'description'
    ];

    public function user()
    {
        return $this->belongsTo('App\Models\Users', 'user_id', 'id');
    }

    public function post()
    {
        return $this->belongsTo('App\Models\Posts', 'post_id', 'id');
    }
}

你必须仔细阅读这本书

在构建API时,您可能需要一个转换层,它位于雄辩的模型和实际返回给应用程序用户的JSON响应之间。Laravel的资源类允许您以表达的方式轻松地将模型和模型集合转换为JSON

文档编写良好,易于理解。它应该有你需要的一切


你需要阅读这一章,这一章解释了如何处理人际关系。

你必须仔细阅读

在构建API时,您可能需要一个转换层,它位于雄辩的模型和实际返回给应用程序用户的JSON响应之间。Laravel的资源类允许您以表达的方式轻松地将模型和模型集合转换为JSON

文档编写良好,易于理解。它应该有你需要的一切


您需要阅读本章,其中解释了如何处理关系。

您需要进行两项更改

1) 从post表中删除post_id并将其放置在注释表中

2) 编写查询

Post::with('comment','user')->get();

你需要做两个改变

1) 从post表中删除post_id并将其放置在注释表中

2) 编写查询

Post::with('comment','user')->get();

你的第一张桌子是波斯特的桌子还是错了?我想第一个是评论表,第二个可能是帖子表。你们的第一个表是帖子表还是搞错了?我想第一个是评论表,第二个可能是帖子表。谢谢。我通过查看有关资源的文档解决了我的问题。谢谢。我通过查看有关资源的文档解决了我的问题。