急切加载用户对象内部的嵌套对象

Eagar Loading A Nested Object Inside of a User Object

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

<?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');
    }
}

这是当前 returned 的 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 {
            ...
        }
    }
}

模型关系不执行查询,但它允许您访问 dynamic properties

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

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

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

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

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