以下是一个示例,展示了如何在 Backpack for Laravel 中定义相关的模型关系,并使用中间表进行多对多关联,并在删除主模型时自动删除中间表中对应的条目。
class Author extends Model
{
public function books()
{
return $this->belongsToMany(Book::class)->withTimestamps();
}
}
class Book extends Model
{
public function authors()
{
return $this->belongsToMany(Author::class)->withTimestamps();
}
}
// 中间表 authors_books
Schema::create('authors_books', function (Blueprint $table) {
$table->integer('author_id')->unsigned();
$table->foreign('author_id')->references('id')->on('authors')->onDelete('cascade');
$table->integer('book_id')->unsigned();
$table->foreign('book_id')->references('id')->on('books')->onDelete('cascade');
$table->timestamps();
});
// 在 Author 和 Book 模型中添加以下代码,以在删除主模型时自动删除相关中间表条目
class Author extends Model
{
public static function boot()
{
parent::boot();
static::deleting(function ($author) {
$author->books()->detach();
});
}
}
class Book extends Model
{
public static function boot()
{
parent::boot();
static::deleting(function ($book) {
$book->authors()->detach();
});
}
}