如何删除laravel 4.2中的关系数据

时间:2014-08-27 11:50:02

标签: laravel laravel-4 eloquent

我有两个名为usercustomer的表。

现在,当我删除子数据时,如何删除父数据?

就像我跑$customer->delete();时一样 我想从user user.id = customer.user_id

中删除

用户模型

use Illuminate\Auth\UserInterface;
use Illuminate\Database\Eloquent\SoftDeletingTrait;

class User extends Eloquent implements UserInterface {
    use SoftDeletingTrait;
    protected $table = 'users';
    public $timestamps = true;
    protected $dates = ['deleted_at'];
}

客户模式

use Illuminate\Database\Eloquent\SoftDeletingTrait;

class Customer extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
        use SoftDeletingTrait;
        protected $table = 'customers';
        public $timestamps = true;
        protected $dates = ['deleted_at'];

        public function User(){
            return $this->belongsTo('user','user_id','id');
        }
}

1 个答案:

答案 0 :(得分:1)

Eloquent中有Model Events可用,例如:

class Customer extends Eloquent {

    public static function boot()
    {
        parent::boot();

        static::deleting(function($customer) {
            // This will delete parent item
            // before it deletes child item
            $customer->user()->delete();
        });
    }
}

所以,当你打电话给这样的话时:

Customer::find(1)->delete();

首先删除父项User,然后删除子项Customer