問題描述
當我使用 eloquent 時,我可以使用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.
推薦答案
如果您只需要從模型的數組或 JSON 表示中隱藏屬性,您可以使用一種或兩種方法:
If you only need to hide attributes from your model's array or JSON representation, you may use one or both approaches:
- 添加
$hidden
屬性給你的模型
- Add the
$hidden
property to your model
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 響應中隱藏數據會更方便.
See other answers for more details... But sometimes you don't want to load huge data (geospatial, html, logs...) into your application, it will be slow and take more memory. OP asked for an SQL query hence my answer, but most of the time it's more convenient to only hide the data from the JSON response.
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
更新
另一個技巧是指定模型中的所有列(或使用額外的查詢來使用 $this->getTableColumns()
從 這個答案,也可以在每次遷移后緩存以避免兩次查詢)然后添加一個局部作用域 函數
Another trick is to specify all columns in your model (or use an extra query to get all columns using $this->getTableColumns()
from this answer, it can also be cached after each migration to avoid two queries) then add a local scope function
// 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();
這篇關于如何在使用 eloquent 時排除某些列的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!