【发布时间】:2020-01-06 13:09:44
【问题描述】:
我的模型类中有一些关系。
消费这种关系:
我们有 Post() 模型来存储我们的帖子数据。此表中的每个帖子都有一个user_id 列,与User() 模式(帖子的作者)具有一对多关系
class User extends Model {
public function posts()
{
return $this->hasMany('App\Post');
}
}
class Post extends Model {
public function user()
{
return $this->belongsTo('App\User');
}
}
所以当我想用 elequent 回复我的帖子时,我会得到这样的东西:
{
"user_id": 1,
"title": "Foo name",
"body": "Foo body",
},
{
"user_id": 1,
"title": "Bar name",
"body": "another Bar body",
}
但我想得到这样的东西:
{
"user_id": 1,
"user": {
'name'=> 'John',
'last'=> 'Maco',
},
"title": "Foo name",
"body": "Foo body",
},
{
"user_id": 1,
"user": {
'name'=> 'John',
'last'=> 'Maco',
},
"title": "Bar name",
"body": "another Bar body",
}
【问题讨论】:
-
类似:
Post::with('user')->get()应该可以工作。看这里:laravel.com/docs/5.8/eloquent-relationships#eager-loading -
@dparoli 谢谢你,这就是我想要的
-
不客气,您的关系已经有了正确的命名约定,因此查询很容易。