简体   繁体   English

如何获取laravel 5.1中更新字段的总数?

[英]How to get the total number of updated fields in laravel 5.1?

I need to save the number of fields updated after an update operation is performed on a model and its related models. 我需要保存在模型及其相关模型上执行更新操作后更新的字段数。

Suppose I have a user profile edit form. 假设我有一个用户配置文件编辑表单。 On that form I allow the user to update its firtname, lastname, password. 在该表单上,我允许用户更新其firtname,lastname,password。

The User model has email and password fields and few other fields as well. 用户模型还包含电子邮件和密码字段以及其他一些字段。

The UserProfile model has firstname, last name and other fields as well. UserProfile模型也有名字,姓氏和其他字段。

The User model is associated with UserProfiles model with hasOne association. User模型与具有hasOne关联的UserProfiles模型相关联。

There are some ManyToMany and hasMany associations as well. 还有一些ManyToMany和hasMany关联。

If the user updates firstname and password I need to show user the "number of fields changed : 2". 如果用户更新了名字和密码,我需要向用户显示“更改的字段数:2”。

Is there any Laravel 5 way or package to do so. 是否有任何Laravel 5方式或包装。

Thanks. 谢谢。

You can use the getDirty() method of the Eloquent model like this: 您可以使用Eloquent模型的getDirty()方法,如下所示:

$data = ['email' => 'email@example.com', 'name' => 'John Doe'];
$user = User::find(1);

$user->fill( $data );

if ( !$user->isDirty() ) {
    //NO DATA CHANGED
}

$numberOfChanges = count( $user->getDirty() );

The getDirty() will return an array of the changed properties of the model, so when you count the size of the array you'll have exactly how many fields there were changed. getDirty()将返回模型的已更改属性的数组,因此当您计算数组的大小时,您将确切地知道有多少字段已更改。

Please note that I've used the User model only for example and $data would probably come from the request. 请注意,我仅使用User模型作为示例, $data可能来自请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM