Laravel 5 - 从模型关系查询返回完整对象

时间:2016-10-25 22:02:36

标签: laravel laravel-5 laravel-5.2

我的模型看起来像:

class User extends Model{

    public function projects(){

        $this->hasMany('Project', 'project_id')

   }

}

当我在初始化类之后通过调用$user->projects()->get()来使用上述方法时,我只收集了与项目相关的信息:

Object [attributes:protected] => array(
     [project_name] => 'my project',
     [project_description] => 'my other project',
     [created_at] => '11-22-2015 04:23:12'
)

如何获得包含项目和用户数据的集合?我正在寻找类似的东西:

Object [attributes:protected] => array(
     [user_name] => 'macdadd',
     [user_type] => 4,
     [created_at] => '11-22-2015 04:23:12',
     [project] => array(
         array(
             [project_name] => 'my project',
             [project_description] => 'my other project',
             [created_at] => '11-22-2015 04:23:12'
         )
     )
)

1 个答案:

答案 0 :(得分:1)

为此,您应该可以使用预先加载:

$user->with('projects')->get()

请参阅:https://laravel.com/docs/5.3/eloquent-relationships#eager-loading