使用雄辩时如何排除某些列 [英] How to exclude certains columns while using eloquent

查看:100
本文介绍了使用雄辩时如何排除某些列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用雄辩时,我可以使用where方法,然后方法get来填充包含我在数据库中选择的对象。
我的意思是:

When I'm using eloquent, I can use the "where" method then the method 'get' to fill an object containing what I've selected in my database. I mean:

$users = User::where('gender', 'M')->where('is_active', 1)->get(['pseudo', 'email', 'age', 'created_at'])->toArray();

这里我可以选择我想要的列伪,电子邮件等
但是我在laravel doc中想到的是做相反的方式。
它可能是这样的:

Here I can choose the columns I want to get like 'pseudo', 'email', etc.. But what I miss in laravel doc is the way to do the contrary. It could be something like that:

$users = User::where('gender', 'M')->where('is_active', 1)->notGet(['pseudo', 'email', 'age', 'created_at'])->toArray();

谢谢你的未来答案,祝一个愉快的一天。

Thank you for you futur answer and have a nice day.

推荐答案

AFAIK在SQL中没有内置的选项来明确排除列,所以Laravel无法做到这一点。但您可以尝试这个技巧

AFAIK there is no build in option in SQL to exclude columns explicitly, so Laravel can't do it. But you can try this trick

更新

另一个诀窍是指定模型中的所有列

Another trick is to specify all columns in your model

protected $columns = array('id','pseudo','email'); // add all columns from you table

public function scopeExclude($query,$value = array()) 
{
    return $query->select( array_diff( $this->columns,(array) $value) );
}

然后你可以做:

$users = User::where('gender', 'M')->where('is_active', 1)->exclude(['pseudo', 'email', 'age', 'created_at'])->toArray();

这篇关于使用雄辩时如何排除某些列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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