php 如何在使用 eloquent 时排除某些列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23612221/
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-08-25 16:50:27  来源:igfitidea点击:

How to exclude certains columns while using eloquent

phplaraveleloquent

提问by Brazeredge

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:

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

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

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:

在这里,我可以选择我想要的列,如“伪”、“电子邮件”等。但我在 laravel doc 中想念的是相反的方法。它可能是这样的:

$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.

谢谢你未来的回答,祝你有美好的一天。

回答by Razor

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

AFAIK 在 SQL 中没有内置选项来明确排除列,所以 Laravel 不能这样做。但是你可以试试这个技巧

Update

更新

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

Then you can do :

然后你可以这样做:

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

回答by Christhofer Natalius

I don't know about previous Laravel version, but in 5.4 you can put this line in User model

我不知道以前的 Laravel 版本,但是在 5.4 中,您可以将此行放在 User 模型中

protected $hidden = ['pseudo', 'email', 'age', 'created_at'];

and then User::find(1);will return all fields except pseudo, email, age, and created_at.

然后User::find(1);将返回除了各个领域pseudoemailage,和created_at

But you still can retrieve those hidden fields by using:

但是您仍然可以使用以下方法检索这些隐藏字段:

$user = User::find(1);
$email = $user['email']; // or $user->email;

回答by sajed zarrinpour

using hiddenarray in model is good, but if you don't want to hide your column all the time and use makeVisibleto access them in need, then instead, hide your column from serialization where you need with makeHiddenfunction like this :

hidden在模型中使用数组很好,但是如果您不想一直隐藏您的列并使用它makeVisible来访问需要的它们,那么相反,使用如下makeHidden函数将您的列隐藏在您需要的序列化中:

$res = Model::where('your query')->get();
$res->makeHidden(['column_one','column_two','column_n']);
return response()->json($res);

回答by vuhung3990

you can use hiddenarray like this:

你可以hidden像这样使用数组:

class Promotion extends Model
{
    protected $table = 'promotion';
    protected $hidden = array('id');
}

回答by Rafael Xavier

We get the object eloquent from the model full with all fields, transform it to array and we put it inside of a collection. Than we get all fields except all fields specified in array $fields.

我们从包含所有字段的模型中获取 eloquent 对象,将其转换为数组,然后将其放入集合中。然后我们得到除了数组 $fields 中指定的所有字段之外的所有字段。

$fields = ['a', 'b', 'c', 'N'];
$object = Model::find($id);
return collect($object->toArray())->except($fields);

More clearly, let's give an example:

更清楚一点,我们举个例子:

// Array of fields you want to remove
$fields_to_remove = ['age', 'birthday', 'address'];

// Get the result of database
$user = User::find($id);

// Transform user object to array
$user = $user->toArray();

// Create a collection with the user inside
$collection = collect($user);

// Get all fields of our collection except these fields we don't want
$result = $collection->except($fields_to_remove);

// Return
return $result;

This example above makes exactly the same thing of the first one, but it's more explained.

上面的这个例子和第一个例子完全一样,但解释得更清楚。

回答by Manojkiran.A

I have looked into the answer by @Razor

我查看了@Razor 的答案

But there is Very Conveinent way by skipping $columns property

但是通过跳过 $columns 属性有一种非常方便的方法

/**
     * Scope a query to only exclude specific Columns
     *
     * @param  \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeExclude($query, ...$columns) 
    {
        return $query->select( array_diff( $this->getTableColumns(),$columns) );
    }

    /**
     * Shows All the columns of the Corresponding Table of Model
     *
     * @author Manojkiran.A <[email protected]>
     * If You need to get all the Columns of the Model Table.
     * Useful while including the columns in search
     * @return array
     **/
    public function getTableColumns()
    {
        return $this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable());
    }

getTableColumnsfunction will get all the columns of the table so you dont need to define the

getTableColumns函数将获取表的所有列,因此您无需定义

$column property

$column 属性

回答by dastan

You can use unset unset($category->created_at,$category->updated_at);

您可以使用未设置 unset($category->created_at,$category->updated_at);

$fcategory = array();
$kCategory = KCategory::where("enabled", true)->get();
foreach ($kCategory as $category) {
    $subkCategory = PostCategory::select("id", "name", "desc")
        ->where("id_kcategory", $category->id)
        ->where("enabled", true)
        ->get();

    unset($category->created_at, $category->updated_at);

    $fcategory[] = $category;
}