首先使用查询构建器 [英] Pluck together with first using Query builder

查看:30
本文介绍了首先使用查询构建器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想使用 eloquent 获取数据库中第一个用户的姓名,我可以这样做:

If I want to get get name of first user in database using eloquent I can do something like that:

$user =  User::select('name')->first()->pluck('name');
// or $user =  User::first()->pluck('name');

echo $user;

仅以字符串形式获取此用户的名称.

to get only name of this user as string.

但是,如果我仅使用查询构建器尝试相同的操作:

However If I try the same using only query builder:

$user =  DB::table('users')->select('name')->first()->pluck('name');

echo $user;

我得到异常:

调用未定义的方法 stdClass::pluck()

Call to undefined method stdClass::pluck()

但不先使用它会起作用:

But without using first it will work:

$user =  DB::table('users')->select('name')->where('id',1)->pluck('name');

echo $user;

使用查询构建器无法将 pluckfirst 一起使用,还是我做错了什么?

Is it not possible to use pluck with first using query builder or am I doing something wrong?

附注.当然我知道我可以使用 $user->name 显示任何属性而不使用 pluck 但我只是好奇为什么使用 Eloquent 它可以工作并使用 Query Builder 它仅在没有 firstpluck

PS. Of course I know that I can display any property using $user->name without using pluck but I'm just curious why using Eloquent it works and using Query Builder it works only when not having both first and pluck

推荐答案

你不想将 pluckfirst 一起使用,因为它是多余的:

You don't want to use pluck with first, because it's redundant:

$query->first() // fetch first row
      ->pluck('name'); // fetch first row again and return only name

所以只使用pluck:

$query->pluck('name');

它可以满足您的所有需求.

It does all you need.

但还有更多.

在幕后 firstpluck 运行 2 个单独的查询,因此:

Under the hood first and pluck run 2 separate queries, so:

$query->where(..)->orderBy(..)->first() // apply where and orderBy
        ->pluck('name'); // no where and orderBy applied here!

所以在pluck之前使用first不仅是多余的,而且会导致意想不到的结果.

So it's not only redundant to use first before pluck, but also it causes unexpected results.

你可以在 Eloquent 查询上链接这些方法,因为它返回一个集合(get)或模型(first),但是 QueryBuilder 只返回一个数组 (get) 或 stdObject (first).这就是为什么你不能在查询构建器上做同样的事情.

You can chain those methods on Eloquent query, since it returns a collection (get) or model (first), but QueryBuilder returns just an array (get) or stdObject (first). That's why you couldn't do the same oon the query builder.

这篇关于首先使用查询构建器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆