Laravel Eager通过中间模型加载

时间:2014-11-06 01:17:54

标签: laravel model eager-loading

在我的一个控制器中,我有以下内容:

return Lot::with(array('region', 'territory', 'manager')) -> get();

这很有效,并返回以下内容:

Array
(
[0] => stdClass Object
    (
        [id] => 1
        [region_id] => 3
        [territory_id] => 2
        [state_id] => 5
        [manager_id] => 2
        [lot_num] => 0
        [lot_type] => managed
        [name] => Some Name
        [address_1] => Some Address
        [address_2] => 
        [address_3] => 
        [city] => Some City
        [zip] => 00000
        [opened_at] => 
        [deleted_at] => 
        [created_at] => 2014-11-06 00:49:39
        [updated_at] => 2014-11-06 00:49:39
        [region] => stdClass Object
            (
                [id] => 3
                [name] => Corporate
                [deleted_at] => 
                [created_at] => 2014-11-06 00:49:39
                [updated_at] => 2014-11-06 00:49:39
            )

        [territory] => stdClass Object
            (
                [id] => 2
                [name] => Corporate
                [deleted_at] => 
                [created_at] => 2014-11-06 00:49:39
                [updated_at] => 2014-11-06 00:49:39
            )

        [manager] => stdClass Object
            (
                [id] => 2
                [email] => test@tester.com
                [active] => 1
                [last_login] => 
                [created_at] => 2014-11-06 00:49:39
                [updated_at] => 
                [deleted_at] => 
            )

    )

)

我的经理' Lot类中的方法具有以下关系:

return $this -> belongsTo('User');

我的User类有以下方法:

public function profile(){
    return $this -> hasOne('Profile');
}

现在,最后我的问题:)是否有可能通过我在第一个代码片段中对我的Lot类进行的急切加载来为这个用户加载配置文件?我想要完成的就是让我的经理'返回中的对象看起来像这样:

[manager] => stdClass Object
            (
                [id] => 2
                [email] => test@tester.com
                [active] => 1
                [last_login] => 
                [created_at] => 2014-11-06 00:49:39
                [updated_at] => 
                [deleted_at] => 
                [profile] => stdClass Object
                (
                    [id] => 5
                    [first_name] => Test
                    [last_name] => Tester
                    ...
                )
            )

1 个答案:

答案 0 :(得分:6)

eager load嵌套关系使用“点”表示法:

return Lot::with(array('region', 'territory', 'manager.profile'))->get();