我有两个名为user
和customer
的表。
现在,当我删除子数据时,如何删除父数据?
就像我跑$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');
}
}
答案 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
。