Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 为什么对User::first()调用方法有效,而User::where(…)无效?_Php_Mysql_Laravel_Laravel Artisan - Fatal编程技术网

Php 为什么对User::first()调用方法有效,而User::where(…)无效?

Php 为什么对User::first()调用方法有效,而User::where(…)无效?,php,mysql,laravel,laravel-artisan,Php,Mysql,Laravel,Laravel Artisan,在php artisan tinker中工作并返回true: >>> User::first()->is('admin'); => true 返回错误: >>> User::where('id', 1)->is('admin'); BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder\::is()' 为

在php artisan tinker中工作并返回true:

>>> User::first()->is('admin');
=> true
返回错误:

>>> User::where('id', 1)->is('admin');
BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder\::is()'

为什么会这样?

因为当使用
->where()
时,您正在构建一个集合,但是
->first()
会返回模型

为了让eloquent返回模型,您需要通过添加一个
->get()

但是,这也会返回一个集合。您可以使用
->first()

编辑评论:

尝试这样做,但是上面的代码应该可以工作

$user = User::where('id', 1)->first();
$isAdmin = $user->is('admin');

在上面的示例中,您定义了您想要的:

User;
 User::where('id', 1);
然后您检索它:

first();
在下面的示例中,您还定义了您想要的:

User;
 User::where('id', 1);
但是,您不会在任何地方检索它。所以现在还不能执行
->is('admin')
,因为您没有进行检查的结果

您可以检索第一个匹配的集合或包含所有匹配项的集合:

User::where('id', 1)->first(); // One result
User::where('id', 1)->get(); // Collection of results
User::first()返回用户类对象

User::where('id',1)返回雄辩的查询对象

这就是它不起作用的原因


但是User::where('id',1)->get()将给出结果行数组。但是调用is()也不起作用。

如其他答案中所述,where()返回查询生成器,where()->get()返回集合。然后可以返回从集合调用的rirst()

$user = User::where('id', 1)->get()->first();
$isAdmin = $user->is('admin');

现在我得到错误:
BadMethodCallException,消息为“方法不存在”。
您在用户模型上有
is
函数吗?请确保您准确复制了代码。以下是我的用户模型的外观-在我的示例中仔细检查您是否复制了代码,如果这不起作用,请尝试在编辑中使用代码。如果您希望通过id获取用户,您还可以使用
User::find($id)
。如果找不到用户::findOrFail($id),则希望获得404。