欢迎各位兄弟 发布技术文章
这里的技术是共享的
find
方法中指定属性- User::find(1, ['name', 'email']);
- User::findOrFail(1, ['name', 'email']);
Clone
一个Model
用replicate
方法可以克隆一个Model
- $user = User::find(1);
- $newUser = $user->replicate();
- $newUser->save();
Model
是否相同检查两个Model
的ID是否相同用is
方法
- $user = User::find(1);
- $sameUser = User::find(1);
- $diffUser = User::find(2);
- $user->is($sameUser); // true
- $user->is($diffUser); // false;
Model
- $user = User::find(1);
- $user->name; // 'Peter'
- // 如果 name 更新过,比如由 peter 更新为 John
- $user->refresh();
- $user->name; // John
Model
- $user = App\User::first();
- $user->name; // John
- //
- $updatedUser = $user->fresh();
- $updatedUser->name; // Peter
- $user->name; // John
Model
在更新关联的时候,使用push
方法可以更新所有Model
- class User extends Model
- {
- public function phone()
- {
- return $this->hasOne('App\Phone');
- }
- }
- $user = User::first();
- $user->name = "Peter";
- $user->phone->number = '1234567890';
- $user->save(); // 只更新 User Model
- $user->push(); // 更新 User 和 Phone Model
Laravel
默认使用deleted_at
作为软删除字段,我们通过以下方式将deleted_at
改成is_deleted
- class User extends Model
- {
- use SoftDeletes;
- * deleted_at 字段.
- *
- * @var string
- */
- const DELETED_AT = 'is_deleted';
- }
或者使用访问器
- class User extends Model
- {
- use SoftDeletes;
- public function getDeletedAtColumn(){
- return 'is_deleted';
- }
- }
Model
更改的属性- $user = User::first();
- $user->name; // John
- $user->name = 'Peter';
- $user->save();
- dd($user->getChanges());
- // 输出:
- [
- 'name' => 'John',
- 'updated_at' => '...'
- ]
Model
是否已更改- $user = User::first();
- $user->name; // John
- $user->isDirty(); // false
- $user->name = 'Peter';
- $user->isDirty(); // true
- $user->getDirty(); // ['name' => 'Peter']
- $user->save();
- $user->isDirty(); // false
getChanges()
与getDirty()
的区别getChanges()
方法用在 save()
方法之后输出结果集getDirty()
方法用在save()
方法之前输出结果集
Model
信息- $user = App\User::first();
- $user->name; //John
- $user->name = "Peter"; //Peter
- $user->getOriginal('name'); //John
- $user->getOriginal(); //Original $user record
来自 https://blog.csdn.net/weixin_41380972/article/details/106897037