首先使用“查询”构建器一起执行 [英] Pluck together with first using Query builder

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

问题描述

如果我想使用雄辩得到数据库中第一个用户的名字,我可以这样做:

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;

无法使用 pluck 第一个使用查询构建器或我做错了?

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

PS。当然,我知道我可以使用 $ user-> name 显示任何属性,而不使用 pluck ,但我只是好奇为什么使用Eloquent它的工作和使用查询生成器,它只有当没有同时第一 pluck

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

推荐答案

您不想使用 pluck 第一个,因为它是多余的:

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');

它需要你所有的。

但还有更多。

在引擎盖下第一 pluck 运行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 之前,也会导致意想不到的结果。

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

你因为它返回一个集合( get )或模型(第一个),而是可以将这些方法链接起来, code> Query\Builder 只返回一个数组( get )或 stdObject first )。这就是为什么你不能在查询构建器中执行相同操作。

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

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

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