Laravel eloquent 添加自定义查询元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26984261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:26:29  来源:igfitidea点击:

Laravel eloquent add custom query elements

phpmysqllaravelormeloquent

提问by CMOS

So I am having some trouble with size and server requests. So I am trying to get a minified version of a row from eloquent. So for example here is my query call

所以我在大小和服务器请求方面遇到了一些问题。所以我试图从 eloquent 中获得一行的缩小版本。所以例如这里是我的查询电话

$user = User::where('email', '=', '[email protected]')->first();

This works but returns a ton of information. Stuff that I do not need, relations, observables, dates, guarded status, fillable AND every single column. This is expected so If I want to get first and last name and email. I could do something like this

这有效,但会返回大量信息。我不需要的东西,关系,可观察的,日期,受保护的状态,可填写的和每一列。这是意料之中的,所以如果我想获得名字和姓氏以及电子邮件。我可以做这样的事情

$users = DB::table('users')->select('firstname','lastname', 'email')->get();

And this would work, except I don't want to type that every single time I wanna do this. Is it possible for me to setup somewhere in eloquent or in my model so that I can do

这会奏效,但我不想每次都输入它。我是否可以在 eloquent 或我的模型中设置某个地方,以便我可以做

$user = User::where('email', '=', '[email protected]')->min()->first();

Simply add a custom function called min() that only grabs those three values. Is something like this possible?

只需添加一个名为 min() 的自定义函数,该函数仅获取这三个值。这样的事情可能吗?

回答by The Alpha

Yes, you can do it if you declare a method in your Usermodel like this:

是的,如果你在你的User模型中声明一个方法,你可以这样做:

// User.php
public function scopeMin($query)
{
    return $query->select('firstname','lastname', 'email');
}

Then you can use it like this (To get only 'firstname','lastname', 'email'):

然后你可以像这样使用它(仅获取'firstname','lastname', 'email'):

$user = User::where('email', '=', '[email protected]')->min()->first();

Read about Query Scopeon the documentation.

阅读文档中的查询范围

回答by bgallagh3r

You can limit the columns by passing an array in the first() method.

您可以通过在 first() 方法中传递一个数组来限制列。

$user = User::where('email', '=', '[email protected]')->first(['firstname','lastname', 'email']);

回答by Pantelis Peslis

You can insert the $hidden array at your model, with the columns that you don't want to appear.

您可以在模型中插入 $hidden 数组,以及您不想显示的列。