find
方法中指定屬性User::find(1, ['name', 'email']); User::findOrFail(1, ['name', 'email']);
Clone
一個Model
用replicate
方法能夠克隆一個Model
this
$user = User::find(1); $newUser = $user->replicate(); $newUser->save();
Model
是否相同檢查兩個Model
的ID是否相同用is
方法code
$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
get
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
string
class User extends Model { use SoftDeletes; * deleted_at 字段. * * @var string */ const DELETED_AT = 'is_deleted'; }
或者使用訪問器io
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()
方法以前輸出結果集function
Model
信息$user = App\User::first(); $user->name; //John $user->name = "Peter"; //Peter $user->getOriginal('name'); //John $user->getOriginal(); //Original $user record