【发布时间】:2021-10-31 21:42:24
【问题描述】:
我在一个 Laravel 8 项目中工作,我有一个名为 PingTest 的模型和一个名为 PingTestEntry 的链接模型。
当 PingTest 被删除时,无论是通过软删除(我已经设置好了)还是通过强制删除,我希望我的所有 PingTestEntry 记录也会被删除,但这不会发生我很难理解为什么。
我会附上我的模型
PingTest
<?php
namespace App\Models\Tools;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;
class PingTest extends Model
{
use HasFactory, SoftDeletes;
/**
* Indicates if the model's ID is auto-incrementing.
*
* @var bool
*/
public $incrementing = false;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'ping_tests';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'id',
'url',
'shareable_id'
];
/**
* The relationships that should always be loaded.
*
* @var array
*/
protected $with = [
'entries'
];
/**
* Get the comments for the blog post.
*/
public function entries()
{
return $this->hasMany(PingTestEntry::class, 'test_id')->orderBy('created_at', 'asc');
}
/**
* Model to get
*/
public function pingTestEntries() {
return $this->hasMany(PingTestEntry::class);
}
/**
* The "booted" method of the model.
*
* @return void
*/
protected static function booted()
{
static::deleted(function ($model) {
$model->pingTestEntries()->delete();
});
}
}
PingTestEntry
<?php
namespace App\Models\Tools;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class PingTestEntry extends Model
{
use HasFactory;
/**
* Indicates if the model's ID is auto-incrementing.
*
* @var bool
*/
public $incrementing = false;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'ping_test_entries';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'id',
'test_id',
'reply_from',
'bytes',
'time',
'ttl'
];
/**
* Get the PingTest that owns the comment.
*/
public function pingTest()
{
return $this->belongsTo(PingTest::class);
}
}
然后,在 Tinker 中,但可以很容易地通过任务/cron,我删除了一个 PingTest,它与条目的 with 关系自动加入:
App\Models\Tools\PingTest::where('id', '79b2aa35-89ce-46d7-93c9-3fda0e0a1417')->delete();
我在这里缺少/需要更改什么?
【问题讨论】:
-
检查this
-
如果您向下滚动到我的
PingTest模型的末尾,您会看到我已经在执行您在booted函数中附加的内容。请注意,您链接的文章是几年前的文章,如上所述,我使用的是最新版本的 Laravel,版本 8。