Eagle正在用户对象内部加载嵌套对象


Eagar Loading A Nested Object Inside of a User Object

我正在尝试使用我的ProfilesController,这样它就会返回我需要的所有必要数据,这样我就可以在从数据库返回数据后将其传递给我的视图。通过它在我的控制器中显示方法,从我的用户模型返回数据,然后从配置文件加载数据,我希望它确保在配置文件数组中添加嵌套的社交链接数组。

<?php namespace App'Http'Controllers;
use App'Http'Requests;
use App'Http'Controllers'Controller;
use App'User;
use Illuminate'Http'Request;
class ProfilesController extends Controller {
    /**
    * Display the specified resource.
    *
    * @param int $id
    * @return Response
    */
    public function show($username)
    {
        $user = User::with('profile')->whereUsername($username)->firstOrFail();
        return $user;
        return view('profile', compact('user'));
    }
}
<?php namespace App;
use Illuminate'Database'Eloquent'Model;
class UserProfile extends Model {
    /**
     * The database table used by the model.
     *
     * @var string
     */
     protected $table = 'user_profiles';
    /**
     * Assigns the relationship between a user proifle and their social  links.
     *
     * @return mixed
     */
    public function social_links()
    {
        return $this->hasOne('App'UserProfileSocialLinks');
    }
}

这是当前返回的JSON对象。

{
    id: 1,
    created_at: "2015-03-28 21:25:19",
    updated_at: "2015-03-28 21:25:19",
    deleted_at: null,
    profile: {
        id: 1,
        user_id: 1,
        bio: "This is just my personal biography!",
        created_at: "2015-03-28 21:25:34",
        updated_at: "2015-03-28 21:25:34",
        deleted_at: null
    }
}

我希望JSON对象显示如下:

{
    id: 1,
    created_at: "2015-03-28 21:25:19",
    updated_at: "2015-03-28 21:25:19",
    deleted_at: null,
    profile: {
        id: 1,
        user_id: 1,
        bio: "This is just my personal biography!",
        created_at: "2015-03-28 21:25:34",
        updated_at: "2015-03-28 21:25:34",
        deleted_at: null,
        social_links {
            ...
        }
    }
}

如果你想添加嵌套关系,你需要在with中这样指定它们:

 $user = User::with('profile.social_links')->whereUsername($username)->firstOrFail();

通过这种方式,您将加载配置文件以及配置文件的social_links。

或者,您可以在Profile类中创建自定义toArray方法来加载所有必需的关系。

模型关系不执行查询,但它允许您访问动态属性。

您可以将联接子句添加到查询中,以便将子查询属性获取到结果中。