Laravel多对多关系-分离所有并删除(如果未附加其他内容)

时间:2019-06-29 19:50:49

标签: laravel postgresql eloquent

在laravel中,我在节点和用户之间建立了多对多关系:

节点

    public function up()
    {
        Schema::create('nodes', function (Blueprint $table) {
            $table->bigIncrements('id')->index();

            $table->string('syncState')->nullable();
            $table->integer('jsonRpcPort')->nullable();
            $table->string('addr')->unique()->index();
            $table->BigInteger('height')->nullable();
            $table->string('nodeId')->nullable();
            $table->string('publicKey')->nullable()->index();
            $table->integer('websocketPort')->nullable();
            $table->integer('relayMessageCount')->nullable();
            $table->integer('sversion')->nullable();
            $table->string('version')->nullable();

            $table->timestamps();
        });
    }

在节点模型中:

    public function users()
    {
        return $this->belongsToMany('App\User')->withPivot('hostname', 'label', 'notified_offline', 'notified_outdated', 'notified_stuck');
    }

用户

        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');

            $table->string('name');
            $table->string('email')->unique();
            $table->boolean('verified')->default(false);
            $table->string('password');

            $table->rememberToken();
            $table->timestamps();
        });

在用户模型中:

    public function nodes()
    {
        return $this->belongsToMany('App\Node')->withPivot('hostname', 'label', 'notified_offline', 'notified_outdated', 'notified_stuck');
    }

Node_user

    {
        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 btw。

1 个答案:

答案 0 :(得分:1)

可能最简单的方法是在调用detach()之后进行检查。 Laravel对于枢轴的观察者有点不知所措,因此,如果您仅使用一种方法使用detach(),则可能是detach()操作之后的以下代码。

通常只检查没有用户的节点,然后删除它们,怎么样:

$nodesToDelete= Node::doesntHave('users')->pluck('id')->toArray();
Node::destroy($nodesToDelete);

如果您只想删除那些未连接的ID,请在分离它们之前在数组中收集这些“待分离”的ID,并仅在这些代码的第一行中将whereIn子句添加到其中