Php 3个表之间的拉维关系
因此,我试图获得类别名称,这就是我所拥有的 药片: 类别:id、名称 帖子类别:id、帖子id、类别id post:id,列 我有以下模型: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
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数组元素中显示类别名称。是!!!这就是我想要的关系非常感谢你你是我的英雄!