【问题标题】:Laravel, attaching related data to json responseLaravel,将相关数据附加到 json 响应
【发布时间】:2015-01-30 19:51:14
【问题描述】:

我正在尝试附加角色并返回用户及其角色:

# Attach role depending on input 'type'
$role = Input::get('type');
$user->assignRoleByName($role);

# Return response
return Response::json(array(
    'user' => $user,
    'roles' => $user->roles
));

奇怪的是,当我收到上述回复时,角色包含在“用户”部分“角色”部分中(正如我所想象的那样)。 然而,当我删除“角色”部分时,角色也会从“用户”部分中消失

我想要的是与用户一起返回角色,使用:

# Return response
return Response::json(array(
    'user' => $user
));

在我的 User.php 模型中:

public function roles()
{
    return $this->belongsToMany('Role')->withTimestamps();
}

public function assignRoleByName($name)
{
    $roles = Role::all();

    foreach ($roles as $role)
    {
        if ($role->name == $name) 
        {
            $this->roles()->attach($role);
        }
    }

}

还有数据透视表迁移:

Schema::create('role_user', function(Blueprint $table)
{
    $table->increments('id');
    $table->integer('role_id')->unsigned()->index();
    $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
    $table->integer('user_id')->unsigned()->index();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->timestamps();
});

我在这里做错了什么?

【问题讨论】:

    标签: laravel laravel-4


    【解决方案1】:

    试试类似的,

    $userId = 1; // find the user
    $userWithRoles = $user->with('roles')->where('id' , '=', $userId)->get()->toArray(); // get all roles of the user with user details.
    
    return Response::json(array(
        'user' => $userWithRoles
    ));
    

    不要忘记将 2 表与外键关联。

    【讨论】:

    • 为什么在主键上使用where 方法? find 方法是为了让它更干净
    【解决方案2】:

    你可以试试这个(使用load):

    # Return response
    return Response::json(array(
        'user' => $user->load('roles')
    ));
    

    如需更多信息,请查看Eager LoadingEloquent 中的Lazy Eager Loading 部分。

    【讨论】:

      猜你喜欢
      • 2021-05-26
      • 2019-04-30
      • 1970-01-01
      • 2012-03-23
      • 1970-01-01
      • 2017-09-22
      • 2019-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多