限制 Laravel 中的记录插入
Limit the Insert of Records in Laravel
限制在Laravel
中插入记录
目前我想要实现的是我想将记录限制为 100 现在每当我们尝试插入新记录时我们应该删除一条(第一条)记录并插入新创建的一条
目前我正在像这样手动操作
if(Logs::count() >= 100){ Logs::fist()->delete(); //fuction call again }
else{ Logs::create(); }
我想简化这个并尝试集中化
是的,经过一些研究,我找到了解决方案,我使用了模型观察器
protected static function boot()
{
parent::boot();
static::created(function ($model) {
/* Getting the log limt */
$setting = Setting::where(['option' => 'log_queue_size'])->first();
if ($setting) {
$limit = $setting->value['log_queue_size'] ?? 100;
$logQuery = Log::get();
$keepIds = $logQuery->take($limit)->pluck('id');
Log::whereNotIn('id', $keepIds)->delete();
}
});
}
您不需要从数据库中获取所有记录您只需要记录数
/**
* The "booting" method of the model.
*
* @return void
*/
protected static function boot()
{
parent::boot();
static::created(function ($model) {
/* Getting the log limt */
$setting = Setting::where(['option' => 'log_queue_size'])->first();
if ($setting) {
$limit = $setting->value['log_queue_size'] ?? 100;
$actualCount = Log::query()->count();
if ($actualCount > $limit) {
$recordsToDelete = $actualCount - $limit;
Log::query()->latest()->take($recordsToDelete)->delete();
}
}
});
}
限制在Laravel
中插入记录目前我想要实现的是我想将记录限制为 100 现在每当我们尝试插入新记录时我们应该删除一条(第一条)记录并插入新创建的一条
目前我正在像这样手动操作
if(Logs::count() >= 100){ Logs::fist()->delete(); //fuction call again }
else{ Logs::create(); }
我想简化这个并尝试集中化
是的,经过一些研究,我找到了解决方案,我使用了模型观察器
protected static function boot()
{
parent::boot();
static::created(function ($model) {
/* Getting the log limt */
$setting = Setting::where(['option' => 'log_queue_size'])->first();
if ($setting) {
$limit = $setting->value['log_queue_size'] ?? 100;
$logQuery = Log::get();
$keepIds = $logQuery->take($limit)->pluck('id');
Log::whereNotIn('id', $keepIds)->delete();
}
});
}
您不需要从数据库中获取所有记录您只需要记录数
/**
* The "booting" method of the model.
*
* @return void
*/
protected static function boot()
{
parent::boot();
static::created(function ($model) {
/* Getting the log limt */
$setting = Setting::where(['option' => 'log_queue_size'])->first();
if ($setting) {
$limit = $setting->value['log_queue_size'] ?? 100;
$actualCount = Log::query()->count();
if ($actualCount > $limit) {
$recordsToDelete = $actualCount - $limit;
Log::query()->latest()->take($recordsToDelete)->delete();
}
}
});
}