In my laravel project I want to use an trait for use an uuid
for the primary keys and make a cascade delete.
There is 2 models : User
and Box
.
An user
can have many Box
and a Box
can have many Box
too. Because I use mysql, the onDelete('cascade')
not work and I need it.
So I override the Boot
method of my models to force it, but now, the Boot method of my trait (UuidIdentifiable
) cannot be called.
The utility of this trait is to generate an uuid
for primary key when I create a new model.
Now, when I want to create a model, when Eloquent insert the values, the database return an error because the Id
of my models is null.
So, override the Boot
on a model should override the Boot
of the traits but how to get the functionnality of the custom Boot
method of my trait and of my models too ?
<!-- language: php -->
class Box extends Model
{
use UuidIdentifiable;
protected $fillable = ['label', 'parent_box_id', 'user_id'];
protected $guarded = [];
public $incrementing = false;
public function owner() {
return $this->belongsTo('App\User', 'user_id');
}
public function parent() {
return $this->belongsTo('App\Box', 'parent_box_id');
}
public function boxes (){
return $this->hasMany('App\box', 'parent_box_id', 'id');
}
protected static function boot() {
parent::boot();
static::deleting(function(Box $box) {
$box->boxes()->delete();
});
}
}
class User extends Authenticatable
{
use Notifiable, UuidIdentifiable;
public $incrementing = false;
protected $fillable = ['username', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
public function boxes (){
return $this->hasMany('App\box', 'user_id', 'id');
}
protected static function boot() {
parent::boot();
static::deleting(function(User $user) {
$user->boxes()->delete();
});
}
}
trait UuidIdentifiable
{
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->{$model->getKeyName()} = Uuid::generate()->string;
});
}
}
from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2npaBHy
via IFTTT
Aucun commentaire:
Enregistrer un commentaire