为什么分离不能立即在我的Laravel模型上工作?

Rai*_*l24 1 php mongodb laravel eloquent laravel-5

这是我的一些代码:

class User extends Model {

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

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

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

        if ($this->orders) {
            echo 'Orders still exist?'
        } 
    }
}
Run Code Online (Sandbox Code Playgroud)

我的回声声明正在被击中.如果我刷新我的应用程序,没有附加订单,但在我"清空"我的购物车后,它立即返回订单,好像我没有删除它们...

有趣的是,返回的"订单"模型已user_id设置为null.

pat*_*cus 7

$this->orders是一个关系属性.加载关系后(通过急切加载或延迟加载),除非在代码中明确完成,否则不会重新加载关系.

因此,在函数的开头,您可以访问该$this->orders属性.如果订单尚未加载,则此时它们将被延迟加载.然后,您将完成并解除用户的订单.这正确地设置user_id为null,并更新数据库(使用您的save()),但它不会从已加载的Collection中删除项目.

如果您希望$this->orders在完成修改关系后该属性反映关系的当前状态,则需要显式重新加载关系.示例如下:

public function emptyCart() {
    // gets the Collection of orders
    $orders = $this->orders;

    // modifies orders in the Collection, and updates the database
    foreach($orders as $order) {
        $order->user()->dissociate();
        $order->save();
    }

    // reload the relationship
    $this->load('orders');       

    // now there will be no orders
    if ($this->orders) {
        echo 'Orders still exist?'
    } 
}
Run Code Online (Sandbox Code Playgroud)