API显示用户详细信息

时间:2019-05-05 12:31:06

标签: laravel api model relationship

我当前的API是:

[{“ id”:43,“ title_id”:1,“ user_id”:1,“ comment”:“ asdasddsa”,“ season”:null,“ episode”:null,“ created_at”:null,“ Updated_at“:”“ 2019-04-30 09:14:15”}]

我想根据ID从用户表中将user_id替换为用户详细信息。我希望看到它:

[{"id":43,"title_id":1,"users":{id:"1",username:"test",email:"example@example.com"},"comment":"asdasddsa","season":null,"episode":null,"created_at":null,"updated_at":"2019-04-30 09:14:15"}]

控制器

public function index($id)
{
    $test = Title::where('title_id', $id)->get();

    return $test;
}

标题模型

public function user()
{
    return $this->belongsTo('App\User', 'user_id');
}

protected $table = 'title';

如果我在控制器中这样使用foreach()

$test = Title::where('title_id', $id)->get(); 
foreach($test as $details) 
{
    return $details->user->username;
}

它获取用户详细信息,但不在API中。如何在API中获得它?

2 个答案:

答案 0 :(得分:0)

您可以这样做:

$test= Title::where('title_id', $id)->get();

据我了解,一个标题只有一个用户,对吗?然后,您可以执行以下操作来检索标题的用户:

$test->user = User::find($test->user_id);

最后在json响应中返回标题:

return response()->json($test, 200);

您的回来将发送您想要的东西,像这样:

[{"id":43,"title_id":1,"users":{id:"1",username:"test",email:"example@example.com"},"comment":"asdasddsa","season":null,"episode":null,"created_at":null,"updated_at":"2019-04-30 09:14:15"}]

希望您很清楚。当然可以根据您的需要进行调整。 Dom

答案 1 :(得分:0)

对于API,最好使用Eloquent resource

标题资源示例如下

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Title extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'title_id' => $this->title_id,
            'title_name' => $this->title_name,
            'user_name' => $this->user->name,
        ];
    }

    public function with($request)
    {
        return  [
            'status' => '200',
            'response' => 'Title resource',
        ];
    }
}

在您的控制器中

 public function show(Title $title)
  {
      return new TitleResource($title);
  }

在5.4中,就像

public function show(Title $title)
{
    $title->user_name = $title->user->name;
    return $title->toJson();
}

它应该可以正常工作

修补匠的示例

>>> $user = App\User::find(1);
=> App\User {#3161
     id: 1,
     name: "superadmin",
     email: "superadmin@example.com",
     created_at: "2018-12-13 12:09:07",
     updated_at: "2018-12-22 06:47:13",
   }
>>> $user->pk = 's';
=> "s"
>>> $user
=> App\User {#3161
     id: 1,
     name: "superadmin",
     email: "superadmin@example.com",
     created_at: "2018-12-13 12:09:07",
     updated_at: "2018-12-22 06:47:13",
     pk: "s",
   }