D'Arcy Rail-Ip
D'Arcy Rail-Ip

Reputation: 11955

Why is detach not working on my Laravel model?

Here is some of my code:

class User extends Model {

    public function orders() {
        return $this->hasMany('App\Order');
    }

    public function emptyCart() {
        $orders = $this->orders;

        for ($i = 0; $i < count($orders); $i++) {
            $order = $orders[$i];
            $this->orders()->detach($order);
        }
    }
}

Yet I am getting an error:

Call to undefined method Jenssegers\Mongodb\Query\Builder::detach()

I also tried dissociate():

Call to undefined method Jenssegers\Mongodb\Query\Builder::dissociate()

Originally I was just going to do $this->orders()->detach() but this also failed.

Upvotes: 2

Views: 5405

Answers (1)

patricus
patricus

Reputation: 62278

The detach() method is only available for many-to-many relationships. What you have defined on your User model is a one-to-many.

If your users/orders relationship is many-to-many, you need to change the relationship definition to:

public function orders() {
    return $this->belongsToMany('App\Order');
}

This also assumes you have a order_user pivot table setup. Once you do this, the detach method will work. All the detach method does is remove the entry in the pivot table that associates the two records, it does not actually delete any order records.

However, if your users/orders relationship is actually one-to-many, then the relationship is defined correctly, but your removal logic needs to be updated. If you would like to delete the orders, you can just call $this->orders()->delete();. However, if don't want to remove the order records, just remove the relationship to the user, you can use the dissociate() method, like so:

public function emptyCart() {
    $orders = $this->orders;

    foreach($orders as $order) {
        $order->user()->dissociate();
        $order->save();
    }
}

The dissociate() method is a method on the belongsTo relationship. All it does is reset the foreign key, so you still need to save the model after calling the method.

Upvotes: 1

Related Questions