合并预加载结果

Merge Eager Loading Result

我想尝试合并预加载的结果:

这是我的结果:

 [{"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合并成一个?

谢谢

您正在寻找的是数组展平。你可以这样做

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

然后像这样调用这个函数(如果它在 class 中,请使用正确的语法调用函数)

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

这会给你想要的结果。 希望这对您有所帮助!