【问题标题】:Eagar Loading A Nested Object Inside of a User Object急切地加载用户对象内的嵌套对象
【发布时间】:2015-03-29 15:52:15
【问题描述】:

我正在尝试使用我的 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 {
            ...
        }
    }
}

【问题讨论】:

    标签: php object laravel laravel-5


    【解决方案1】:

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

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

    这样您将加载个人资料以及个人资料的 social_links。

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 我不确定我是否理解如何执行此操作。
      • 加入是您确实需要的东西,记录在Laravel 但 User::with('profile.social_links') 的(其他)答案可能更容易。
      猜你喜欢
      • 1970-01-01
      • 2014-11-14
      • 1970-01-01
      • 2012-08-03
      • 1970-01-01
      • 1970-01-01
      • 2014-10-13
      • 2014-08-23
      • 2018-09-23
      相关资源
      最近更新 更多