合并预先加载结果

时间:2015-07-31 10:26:24

标签: json laravel laravel-5 laravel-5.1

我想尝试合并来自急切加载的结果:

这是我的结果:

 [{"id":3,"name":"John","email":"john@doe.com","username":"johndoe",
 "user_detail":{"address":"anywhere in the world","country":"Somewhere","city":"Somecity","phones":"012-12345","logo":"cute.jpg","created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00"}}]

我想要实现的是删除用户详细信息并加入所有json,就像这样:

 [{"id":3,"name":"John","email":"john@doe.com","username":"johndoe","address":"anywhere in the world","country":"Somewhere","city":"Somecity","phones":"012-12345","logo":"cute.jpg","created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00"}]

我的模特:

/*User Model*/ 
public function user_detail(){
  return $this->hasOne('App\UserDetail');
}

/*User Detail Model*/ 
public function user(){
  return $this->belongsTo('App\User');
}

我的控制器:

$user= User::with('user_detail')->where('username', $username)->get();

是否有任何合并json的功能成为一个?。

由于

1 个答案:

答案 0 :(得分:3)

您正在寻找的是阵列扁平化。你可以这样做

    function flatten(array $array) { 
        $return = array(); 
        array_walk_recursive($array, function($a,$b) use (&$return) { $return[$b] = $a; }); 
        return $return; 
    }

然后调用此函数(如果在类中使用适当的语法)

$user= User::with('user_detail')->where('username', $username)->get();
$result = flatten($user);

这将为您提供所需的结果。 希望这有帮助!