【问题标题】:Entrust not finding user's roles委托未找到用户的角色
【发布时间】:2014-12-12 21:06:38
【问题描述】:

我的控制器方法中有以下内容可将 JSON 返回到我的视图:

    public function RolesForUser()
    {
        $userid = Input::get('userid');

        $assigned = DB::table('assigned_roles')
                ->select(array('role_id'))
                ->where('user_id', '=', $userid)
                ->get();

        $user = User::find($userid);
        $roles = $user->roles();

        $data = array('assigned' => $assigned, 'roles' => $roles);
        return Response::json($data);
    }

返回以下内容(使用 Fiddler 检查):

{"assigned":[{"role_id":"2"},{"role_id":"3"},{"role_id":"4"}],"roles":{}}

使用查询生成器的 SQL 语句返回正确的结果,但使用 Entrust 的方法(从 Entrust Issue 34 复制,在对我的用户模型进行更改后)不返回任何角色。

我也尝试了this SO question 中的解决方案,但它只是给了我一个 SQL 错误。

我在 Laravel 4.2.11 上出错的任何想法?

我的用户模型:

class User extends Eloquent implements UserInterface, RemindableInterface 
{
use HasRole;

/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'Users';

/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */
protected $hidden = array('Password');

protected $primaryKey = 'UserID';

public $timestamps = false;

/*Standard methods removed for brevity*/

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

【问题讨论】:

  • 看起来用户模型和它的角色之间的关系是以一种不适合你的方式设置的。您可以附加使用的关系方法或特征吗?谢谢!
  • @hannesvdvreken - 我已经添加了我的用户模型的相关位

标签: laravel eloquent


【解决方案1】:

您似乎定义了不应定义的 roles 方法。使用 Trait HasRole 已经将 roles 关系添加到 User 模型中。

看看HasRole 添加到您的模型中的其他内容:https://github.com/Zizaco/entrust/blob/master/src/Entrust/HasRole.php

roles() 方法返回一个关系。建议返回->roles->roles()->get()

希望这会有所帮助。

【讨论】:

  • 有或没有我自己的角色方法 - 它不会返回任何东西。我也尝试重命名它以避免潜在的命名冲突,但没有乐趣。
  • @SteB 尝试删除 () 关闭 $roles = $user->roles();因为这将返回一个查询构建器对象,而不是您期望的集合,因为 Eloquent 通常允许您在使用 () 时重新查询关系。但是按照 hannesvdvreken 所说的去做。
  • 谢谢,我已经用更多信息更新了我的答案。
  • @MattBurrow - 如果我从 $user->roles() 中删除 ();然后我得到一个“在 JsonResponse.php 第 50 行调用 \\Collection::jsonSerialize() 失败”
  • 按照@hannesvdvreken 的建议,尝试像这样添加 ->get() ; $user->roles()->get()
猜你喜欢
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多