Laravel多对多关系-如果没有附加任何其他内容,则全部分离并删除
在laravel中,我得到了节点和用户之间的多对多关系: 节点 在节点模型中:Laravel多对多关系-如果没有附加任何其他内容,则全部分离并删除,laravel,postgresql,eloquent,Laravel,Postgresql,Eloquent,在laravel中,我得到了节点和用户之间的多对多关系: 节点 在节点模型中: public function users() { return $this->belongsToMany('App\User')->withPivot('hostname', 'label', 'notified_offline', 'notified_outdated', 'notified_stuck'); } 使用者 在用户模型中: public
public function users()
{
return $this->belongsToMany('App\User')->withPivot('hostname', 'label', 'notified_offline', 'notified_outdated', 'notified_stuck');
}
使用者
在用户模型中:
public function nodes()
{
return $this->belongsToMany('App\Node')->withPivot('hostname', 'label', 'notified_offline', 'notified_outdated', 'notified_stuck');
}
节点用户
{
Schema::create('node_user', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('node_id');
$table->string('hostname')->nullable();
$table->string('label')->nullable();
$table->timestamp('notified_offline')->nullable();
$table->timestamp('notified_outdated')->nullable();
$table->timestamp('notified_stuck')->nullable();
$table->timestamps();
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
$table->foreign('node_id')
->references('id')->on('nodes')
->onDelete('cascade');
});
}
现在如果我调用$user->nodes()->detach()
要从用户分离所有节点,我还希望-如果没有其他用户连接到-这些节点也应该从数据库中删除
我该怎么做?顺便说一句,我正在使用postgresql。最简单的方法可能是在调用
detach()
后进行检查。Laravel对于轴的观察者来说有点模糊,因此如果您仅在一种方法中使用了detach()
,可能类似于detach()
操作后的以下代码
只检查没有用户的节点,然后删除它们,怎么样
$nodesToDelete= Node::doesntHave('users')->pluck('id')->toArray();
Node::destroy($nodesToDelete);
如果您只想删除那些刚刚未连接的节点,请在分离它们之前在数组中收集这些“待分离”ID,并在上面的第一行代码中仅为这些节点添加WHERE子句
{
Schema::create('node_user', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('node_id');
$table->string('hostname')->nullable();
$table->string('label')->nullable();
$table->timestamp('notified_offline')->nullable();
$table->timestamp('notified_outdated')->nullable();
$table->timestamp('notified_stuck')->nullable();
$table->timestamps();
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
$table->foreign('node_id')
->references('id')->on('nodes')
->onDelete('cascade');
});
}
$nodesToDelete= Node::doesntHave('users')->pluck('id')->toArray();
Node::destroy($nodesToDelete);