1. 在find 方法中指定屬性User::find(1, ['name', 'email']);
User::findOrFail(1, ['name', 'email']);
用replicate 方法可以複製一個Model
$user = User::find(1); $newUser = $user->replicate(); $newUser->save();
3. 判斷兩個Model 是否相同
#檢查兩個Model 的ID是否相同用is 方法
$user = User::find(1); $sameUser = User::find(1); $diffUser = User::find(2); $user->is($sameUser); // true $user->is($diffUser); // false;
4 .重新載入一個Model
$user = User::find(1); $user->name; // 'Peter' // 如果 name 更新过,比如由 peter 更新为 John $user->refresh(); $user->name; // John
$user = App\User::first();$user->name; // John
//
$updatedUser = $user->fresh();
$updatedUser->name; // Peter
$user->name; // John
#在更新關聯的時候,使用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
#7. 自訂軟刪除字段
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';
}}
$user = User::first(); $user->name; // John $user->name = 'Peter'; $user->save(); dd($user->getChanges());// 输出: [ 'name' => 'John', 'updated_at' => '...' ]
$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() 方法用在save() 方法之後輸出結果集 getDirty() 方法用在save() 方法之前輸出結果集
#10. 查詢修改前的Model 資訊$user = App\User::first(); $user->name; //John $user->name = "Peter"; //Peter $user->getOriginal('name'); //John $user->getOriginal(); //Original $user record
以上是你會用Laravel的這10種用法嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!