1. 在find
方法中指定属性
User::find(1, ['name', 'email']);
User::findOrFail(1, ['name', 'email']);
2. Clone
一个Model
用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
5. 加载新的Model
$user = App\User::first();
$user->name; // John
//
$updatedUser = $user->fresh();
$updatedUser->name; // Peter
$user->name; // John
6. 更新带关联的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
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';
}
}
8. 查询Model
更改的属性
$user = User::first();
$user->name; // John
$user->name = 'Peter';
$user->save();
dd($user->getChanges());
// 输出:
[
'name' => 'John',
'updated_at' => '...'
]
9. 查询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()
方法之前输出结果集
10. 查询修改前的Model
信息
$user = App\User::first();
$user->name; //John
$user->name = "Peter"; //Peter
$user->getOriginal('name'); //John
$user->getOriginal(); //Original $user record