【问题标题】:Laravel Eloquent Convert user_id to user infoLaravel Eloquent 将 user_id 转换为用户信息
【发布时间】: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",
}

【问题讨论】:

标签: php laravel eloquent


【解决方案1】:

你需要声明从Post到User的关系

Post.php

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

然后,您将能够加载每个帖子(如 @dparoli 评论)的用户

$post = Post::with('user')->get();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-03
    • 2016-11-23
    • 1970-01-01
    • 1970-01-01
    • 2015-02-24
    • 2019-04-29
    • 2017-03-10
    • 2020-09-19
    相关资源
    最近更新 更多