如果您只需要从模型的数组或JSON表示中隐藏属性,则可以使用一种或两种方法:
有关更多详细信息,请参阅其他答案...But有时你不想加载大量数据(地理空间、html、日志(log)等)在你的应用程序中,它会很慢,占用更多内存.OP要求进行SQL查询,因此我给出了答案,但大多数情况下,只隐藏JSON响应中的数据更方便.
另外,SQL中没有明确排除列的内置选项,所以Laravel无法做到这一点.但你可以试试this trick
Update个
另一个技巧是指定模型中的所有列(或者使用额外的查询从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();