我有很多到很多的关系。支点模型hasMany儿童。当我呼吁对许多人的分离,我也需要删除枢轴模型的孩子。我想使用onDelete(“级联”),但这似乎行不通。我也试过这样做:http://laravel-tricks.com/tricks/using-model-events-to-delete-related-items,但这似乎也不起作用。两种情况都不起作用,可能是因为没有触发破坏事件。
有什么办法让孩子们在我打电话时删除吗?
以下是我的一些代码,以防我犯了错误:
我的枢轴模型:
Schema::create('beer_distributions', function(Blueprint $table)
{
$table->increments('id');
$table->integer('beer_id');
$table->integer('distributor_id');枢轴模型的孩子们:
Schema::create('kegs', function(Blueprint $table)
{
$table->increments('id');
$table->integer('beer_distribution_id');
$table->dropForeign('kegs_beer_distribution_id_foreign');
$table->foreign('beer_distribution_id')
->references('id')
->on('beer_distributions')
->onDelete('cascade');我不知道是否有办法挽救这种方法。我打电话给sync,然后尝试删除这些孩子,但没有意识到父母已经走了,使孩子们无法访问。
$attachments = $beer->distributors()->sync(Input::get('distributors'));
foreach ($attachments['detached'] as $distributor_id) {
BeerDistribution::where('beer_id', '=', $id)
->where('distributor_id', '=', $distributor_id)->first()->destroy();
}更新:只是澄清一下,我有四个模型正在工作。啤酒和经销商有很多到很多的关系。枢轴模型,BeerDistributions,hasMany桶。当我调用sync来更新啤酒分销商时,BeerDistributions会自动删除,我希望同时删除这些啤酒桶。
以下是我的一些模特:
class Beer extends Eloquent {
public function distributors()
{
return $this->belongsToMany('Distributor', 'beer_distributions');
}带有分配器的Beer ^ manyToMany:
class Distributor extends Eloquent {
public function beers()
{
return $this->belongsToMany('Beer', 'beer_distributions');
}枢轴模型.
class BeerDistribution extends Eloquent {
public function kegs()
{
return $this->hasMany('Keg', 'beer_distribution_id');
}有很多桶:
class Keg extends Eloquent {
public function beerDistribution()
{
return $this->belongsTo('BeerDistribution');
}发布于 2015-04-13 18:16:01
这里似乎有些关于枢轴表、分离和级联的混淆。
基本上,分离方法应该是您所需要的全部。它所做的就是通过belongsToMany()关系管理支点表。
因此,如果您执行$keg->distributors()->detach([1,2,3])和$keg->id为5,它将从分发服务器为1、2或3且桶id为5的枢轴中搜索和移除项目。在大多数情况下,您甚至不需要为枢轴表建立一个雄辩的模型。detach()、attach()和sync()将为您处理该表。
删除级联很可能是什么导致您的问题,因为你有它向后。在这种情况下,delete on级联键将放在透视表上。这意味着当您删除父(桶或分发)时,将自动删除枢轴表中属于该父项的那些项。这样可以避免表中的孤立数据。
为什么我说您要向后执行此操作,是因为您将键放在您的kegs表上,这意味着当枢轴表中的项目被删除时,您的桶也会被删除。这很糟糕,完全不是你想要的。删除桶时,要从枢轴表中删除项目。
删除该键,并在您的模式中创建beerDistributions,添加两个键,它们将类似于.$table->foreign('beer_id')->references('id')->on('beers')->onDelete('Cascade'); $table->foreign('distribution_id')->references('id')->on('distributors')->onDelete('Cascade');
如果在分发服务器的表上有一个正在删除的键,也要删除它。应该只有那些外键在枢轴表上。
编辑:从您想要删除桶的方式来看,看起来您引用的是数据透视表中的错误列。
$table->foreign('id')
->references('beer_distribution_id')
->on('beer_distributions')
->onDelete('cascade');https://stackoverflow.com/questions/29611394
复制相似问题