从模型中的两个类返回json

时间:2017-03-08 20:39:30

标签: json laravel laravel-5.3

我正在尝试在模型中使用两个类返回json

public function both()
{
    return $this->belongsToMany(Car::class)->and(Driver::class)->withPivot('type'); // this is wrong 
}

我试图这样做的原因是因为我的功能

public function check()
{
    $user = JWTAuth::parseToken()->authenticate();
    $id = $user->id;
    $result = User::with('both')->where('id', $id)->get();
    return response()->json($result);
}

现在在我的模型中我有这个

public function both()
{
    return $this->belongsToMany(Car::class)->withPivot('type');
}
public function driver()
{
    return $this->belongsToMany(Driver::class)->withPivot('type');
}

但是当both结束时,该函数返回具有不同结构的json。

我的问题是我可以让函数返回一个具有相同结构的json吗?

像这样

 [
{
"id": 4,
"name": null,
"phone": "9000",
"size_of_house": null,
"created_at": "2016-12-04 13:55:52",
"updated_at": "2017-03-08 14:03:44",
"deleted_at": null,
"both": [
  {
    "id": 177,
    "name": "NIS",
    "created_at": "2016-12-27 10:28:29",
    "updated_at": "2016-12-27 10:28:29",
    "pic": "http://localhost:8000/images/1482833485.jpg",
    "pivot": {
      "user_id": 4,
      "car_id": 177,
      "type": "car"
    }
  },

"both": [
  {
    "name": "Abdulaziz Alomhsen",
    "age": "30",
    "created_at": "2017-02-28 09:36:15",
    "updated_at": "2017-03-08 08:46:06",
    "status": "جايه",
    "pic": "http://localhost:8000/images/1488714520.jpg",
    "id": 2,
    "pivot": {
      "user_id": 4,
      "driver_id": 2,
      "type": "driver"
    }
  },

0 个答案:

没有答案