jeudi 29 décembre 2016

Laravel 5.3 - Adding DB:raw to model's 'creating' method

I have a table with different type of documents & looking for a way to insure a sub-counter is always unique for each document type. Model Invoice extends model Documents with global scope and a few accessors. I've added this to Invoice boot method :

static::creating(function(Invoice $invoice) {
  $invoice->subtype = DB::raw("(SELECT MAX(subtype) + 1 FROM Documents as 
Documents2 WHERE type = 4)");
});

This worked as long as there were no foreign key constraints on the table. It seems laravel is splitting SQL querries. First it does the DB:raw part :

insert into `documents` (`subtype`, `updated_at`, `created_at`) values    
((SELECT MAX(subtype) + 1 FROM Documents as Documents2 WHERE type = 4), ?, ?)

then it updates with other values :

update `documents` set `document_no` = ?, .... , `updated_at` = ? where `id` = ?

Now the first part always fails because of foreign keys. Is there a way to do this in 'one go' ?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2hRaSOy
via IFTTT

Aucun commentaire:

Enregistrer un commentaire