Laravel包含无法正常工作的方法


Laravel contains method not working properly

用户和角色之间存在多对多关系。出于某种奇怪的原因,当我执行User::find(1)->roles->contains(2)时,它就是不起作用,总是抛出false(我已经签入了数据库,实际上id为1的用户具有id为2的角色)。

我使用它就像Laravel文档一样:http://laravel.com/docs/5.0/eloquent#collections

我挖掘了contains()方法,并在Illuminate'Database'Eloquent'Collecion.php中找到了它,这里是:

/**
 * Determine if a key exists in the collection.
 *
 * @param  mixed  $key
 * @param  mixed  $value
 * @return bool
 */
public function contains($key, $value = null)
{
    if (func_num_args() == 1 && ! $key instanceof Closure)
    {
        $key = $key instanceof Model ? $key->getKey() : $key;
        return $this->filter(function($m) use ($key)
        {
            return $m->getKey() === $key;
        })->count() > 0;
    }
    elseif (func_num_args() == 2)
    {
        return $this->where($key, $value)->count() > 0;
    }
    return parent::contains($key);
}

就在方法的中间,如果我将return $m->getKey() === $key;改为==,它会突然起作用。这是打字错误吗?我应该在存储库中报告它还是提出提取请求?

附言:它永远不会进入parent::contains(),至少在我的情况下是这样。

这可能是因为您的PHP中安装了错误的MySQL插件。有两个版本:mysqlndlibmysql。第二个曾经给我带来很多麻烦,因为它以字符串的形式从数据库返回数据,即使值是实际的整数。mysqlnd正确地将值返回为整数,因此如果使用$model->id === 2,它将正常工作,而使用libmysql,它将评估为false,因为这是严格检查,$model->id将变为string '2'。这就是我要检查你的代码的依据。尝试转储其中一个角色ID,并检查它是整数还是字符串。