简体   繁体   English

将对象返回为json时访问雄辩的关系

[英]Access eloquent relationships when return object as json

I am currently building a JSON RESTful API with Laravel/Lumen and now trying to access model attributes that are being stored in the relationship of this model 我目前正在使用Laravel / Lumen构建JSON RESTful API,现在尝试访问存储在此模型关系中的模型属性

// I also want to return User->roles
return User::find(1)->first();

Returns: 返回值:

{
  "id": 2,
  "email": '...'
}

I actually found a way but that seems pretty much hacked and not clean 我实际上找到了一种方法,但这似乎被黑了,而且不干净

    // Get user
    $user = User::find($id)->first();

    // Make roles public
    $user->roles = $user->roles;

    // Return object
    return $user;

Returns: 返回值:

{
  "id": 2,
  "email": '...',
  "roles": [
  ...
  ]
}

Is there a better way? 有没有更好的办法? Or is this kind of a security thing where you want to protect your data? 还是您想保护数据的这种安全性? But since you can access the relationship in php why shouldn't it be returned as json object? 但是既然可以在php中访问该关系,为什么不应该将它作为json对象返回呢?

Couldn't find something in the laravel documentation 在laravel文档中找不到任何内容

您可以在关系中使用helper函数with例如:

user::find($id)->with('roles')->first()

The shortest syntax for this will be: 最短的语法是:

User::with('roles')->find($id);

There's no need to use first() in this case 在这种情况下,无需使用first()

尝试这个:

$user = User::with('roles')->where('id',  $id)->first();
public function show(User $user) {
        return $user->load('books');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM