我有两个像这样的雄辩模型:
论坛:
protected $fillable = [
'title',
'description',
'icon_path',
'parent_id',
'display_order',
'forum_is_open',
];
public function mods()
{
return $this->hasMany(ForumModerator::class);
}
ForumModerator:
protected $fillable = [
'forum_id',
'user_id',
];
public function forum()
{
return $this->belongsTo(Forum::class, 'forum_id', 'id');
}
public function user()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
我得到了这样的论坛列表:
return Forum::where('forum_is_open', 1)
->with(['subForums', 'mods.user'])
->orderBy('display_order', 'ASC')
->get();
,结果如下:
{
"id": 52,
"title": "Quia eius dolorem est sunt.",
"description": "Dolore eveniet unde autem debitis. Natus et error quaerat dolor minima.",
"icon_path": null,
"parent_id": null,
"display_order": 1,
"forum_is_open": 1,
"created_at": "2022-11-23T22:34:45.000000Z",
"updated_at": "2022-11-23T22:34:45.000000Z",
"sub_forums": [],
"mods": [
{
"id": 1,
"forum_id": 52,
"user_id": 3,
"created_at": null,
"updated_at": null,
"user": {
"id": 3,
"username": "Monserrat McCullough",
"email": "billy52@example.org",
"display_name": "Vincenza Lebsack",
"signature": null,
"group_id": 1,
"post_count": 0,
"created_at": "2022-11-25T04:15:12.000000Z",
"updated_at": "2022-11-25T04:15:12.000000Z"
}
},
{
"id": 2,
"forum_id": 52,
"user_id": 16,
"created_at": null,
"updated_at": null,
"user": {
"id": 16,
"username": "Prof. Norberto Kohler Sr.",
"email": "zdach@example.net",
"display_name": "Edmund Hickle",
"signature": null,
"group_id": 1,
"post_count": 0,
"created_at": "2022-11-25T04:15:12.000000Z",
"updated_at": "2022-11-25T04:15:12.000000Z"
}
}
]
},
我试图得到每个论坛的mod列表,有一个mod,但没有整个论坛主持人的记录。基本上只是想让用户对象在mod数组中。
我需要如何设置Forum和ForumModerator模型之间的关系来实现这一点?
感谢研究了hasManyThrough()
函数,但未能获得预期的结果
最简单的方法可能是使用forum_moderators
表在Forum
和User
模型之间建立多对多关系:
class Forum extends Model
{
public function users()
{
return $this->belongsToMany(User::class, 'forum_moderators');
}
}
然后你可以简单地加载users
关系。
或者,你也可以使用API资源修改你的响应。