我们可以在 Laravel 的 Attach 方法上使用观察者吗?

Abb*_*hit 3 pivot-table observers observer-pattern laravel laravel-8

我想观察一个数据透视表,其中的行是在特定模型中使用附加方法创建的,有没有办法通过负责创建行的附加方法来观察该数据透视表?

Abb*_*hit 6

经过一段时间的挣扎,我来回答我的问题,

因此,为了观察其行是通过 Attach 方法创建的表,我们需要做 3 件事

1-我们需要创建一个扩展的模型 $Illuminate\Database\Eloquent\Relations\Pivot

2- 使用以下行将模型连接到数据库表:

protected $table = 'data_base_table_name';

3-在与数据透视表相关的每个模型中的BelongsToMany关系末尾使用方法“using”

例子:

假设我们有一个名为 Student 的模型和另一个名为 Group 的模型,我们还有一个名为 group_students 的数据透视表,该表填充有 Attach 方法,因为我们有一个学生 BelongsToMany 组和 Group BelongsToMany Students,

我们需要创建一个名为 GroupStudent 的模型, Illuminate\Database\Eloquent\Relations\Pivot 通过在 GroupStudent 类中添加以下行来扩展并将其链接到 group_students:

protected $table = 'group_student'

之后,我们需要在学生模型和组模型中添加使用方法BelongsToMany关系,如下所示:

public function students()
{
    return $this->BelongsToMany(Student::class)->using(GroupStudent::class);
}
Run Code Online (Sandbox Code Playgroud)

public function groups()
{
    return $this->belongsToMany(Group::class)->using(GroupStudent::class);
}
Run Code Online (Sandbox Code Playgroud)

现在,每当我通过 Attach 方法在 group_students 表中创建一行时,都会观察到这一点并执行创建的方法。