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

标签 php laravel eloquent

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

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

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

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

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

最佳答案

如果您只需要从模型的数组或 JSON 表示中隐藏属性,您可以使用一种或两种方法:

  • 添加 $hidden属性到您的模型
    class User extends Model
    {
        /**
         * The attributes that should be hidden for arrays.
         */
         protected $hidden = ['password'];
    }
    
  • 使用 makeHidden 功能
    $users = $users->makeHidden(['address', 'phone_number']);
    

查看其他答案以获取更多详细信息... 但是有时您不想将大量数据(地理空间、html、日志...)加载到您的应用程序中,这会很慢并且需要更多的内存。 OP 要求 SQL 查询因此我的回答,但大多数时候只隐藏 JSON 响应中的数据更方便。


AFAIK 在 SQL 中没有内置选项来显式排除列,所以 Laravel 不能这样做。但是你可以试试this trick

更新

另一个技巧是指定模型中的所有列(或使用额外的查询从 this answer 中使用 $this->getTableColumns() 获取所有列,也可以在每个列之后缓存迁移以避免两个查询)然后添加 local scope功能

// The below code requires you to define all columns in $columns.
// A better approach is to query the schema of the table and cache it after each  
// migration, for more details: https://stackoverflow.com/a/56425794/3192276

protected $columns = ['id','pseudo','email'];

public function scopeExclude($query, $value = []) 
{
    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();

关于php - 如何在使用 eloquent 时排除某些列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23612221/

相关文章:

php - 数据库 :raw 产生不良结果

laravel - 在 Laravel Blade + Vite 中使用 Vue3 组件

mysql - 如何在eloquent中用LIKE搜索句子中的单词

php - 正则表达式解释 : (? >[^<>]+)

java - 将JAVA程序转换为PHP代码

php - PHP 中的单例对象

php - Laravel if then 条件

php - Symfony 与 CakePHP : which one is closest to PHP

php - 如何在 Laravel Eloquent 中保存 bool 值

php - Laravel Eloquent join vs with