Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 3个表之间的拉维关系_Php_Laravel_Eloquent_Relationship - Fatal编程技术网

Php 3个表之间的拉维关系

Php 3个表之间的拉维关系,php,laravel,eloquent,relationship,Php,Laravel,Eloquent,Relationship,因此,我试图获得类别名称,这就是我所拥有的 药片: 类别:id、名称 帖子类别:id、帖子id、类别id post:id,列 我有以下模型:Post、PostCategory和Category 后模型: public function categories() { return $this->hasMany('App\PostCategory'); } 后分类模型: public function category() { return $this->hasMany

因此,我试图获得类别名称,这就是我所拥有的 药片:

类别:id、名称

帖子类别:id、帖子id、类别id

post:id,列

我有以下模型:
Post
PostCategory
Category

后模型:

public function categories()
{
    return $this->hasMany('App\PostCategory');
}
后分类模型:

public function category()
{
    return $this->hasMany(Category::class, 'id', 'category_id');
}
在控制器里我有

return Post::with('categories.category')->orderby('id','desc')->get();
我的结果是

 [
  {
    "id": 50,
    "categories": [
      {
        "id": 92,
        "category_id": 11,
        "category": [
          {
            "id": 11,
            "name": "JXrfLHdQVNON",
            "image": null
          }
        ]
      }
    ]
  }
]
我希望它是这样的

[
  {
    "id": 50,
    "categories": [
      {
        "id": 1,
        "name": "category_name",
        "image": null
      }
    ]
  }
]

有办法吗?我一直在玩弄这件事,还没有找到一个简单的方法来做这件事

这是一种多对多的关系。确保你的关系设置正确。如果要选择特定列,可以执行以下操作:

return Post::with('categories.category:id,name')->orderby('id','desc')->get();
它将返回类别表/模型中的
id、name
列。必须指定执行该操作的
id


在您的帖子模型中:

 public function categories()
 {
        return $this->belongsToMany('App\Model\Category','post_categories','post_id','category_id')->withTimestamps();
 }
在控制器中:

return Post::with('categories:id,name,image')->orderBy('id','desc')->get();

这将在数组“categories”中返回一个名为“categories”的数组。我的想法是在每个categories数组元素中显示类别名称。是!!!这就是我想要的关系非常感谢你你是我的英雄!