【问题标题】:Merge Eager Loading Result合并急切加载结果
【发布时间】:2015-10-22 23:58:59
【问题描述】:

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

这是我的结果:

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

谢谢

【问题讨论】:

    标签: json laravel laravel-5 laravel-5.1


    【解决方案1】:

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

        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);
    

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

    【讨论】:

      猜你喜欢
      • 2013-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-01
      • 2018-09-03
      • 1970-01-01
      相关资源
      最近更新 更多