我的模型看起来像:
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'
)
)
)
答案 0 :(得分:1)
为此,您应该可以使用预先加载:
$user->with('projects')->get()
请参阅:https://laravel.com/docs/5.3/eloquent-relationships#eager-loading