Laravel10个有用的用法

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

你可能感兴趣的:(laravel,eloquent)