Bumping this question. Is there really no way of doing it?
Manual auto increment based on another field
Hey everyone!
I have a table which has three columns: id (primary key, auto incrementing), inner_id and process_id When I insert a new record on the table I need to set the inner_id based on the process_id, sort of like this:
Record ID 1 belongs to Process ID 1 and has an inner ID of 1
Record ID 2 belongs to Process ID 1 and has an inner ID of 2
Record ID 3 belongs to Process ID 1 and has an inner ID of 3
Record ID 4 belongs to Process ID 2 and has an inner ID of 1
Record ID 5 belongs to Process ID 1 and has an inner ID of 4
Record ID 6 belongs to Process ID 2 and has an inner ID of 2
Record ID 7 belongs to Process ID 2 and has an inner ID of 3
Record ID 8 belongs to Process ID 3 and has an inner ID of 1
So what i'm doing is a mutator in the table's model:
public function setInnerIdAttribute($value)
{
if(!$value || $value == 0){
$this->attributes['inner_id'] = Instance::where('process_id', $this->attributes['process_id'])->max('inner_id') + 1;
}
}
On every record I create I get the number 0 on the inner_id field. I know this isn't the way to do it, but any help in this matter would be appreciated. What way is the cleanest? I also thought of creating a method called setInnerId, which I would call on each created object to set the value. Its very important that it ONLY works on inserts, since once its set the inner_id shouldn't be changed to another value.
Just use model observers, and calculate the ids on creating observer.
Here the setter doesn't work because... As this field is auto-generated, it never gets assigned to the object, so the mutator isn't fired.
Please or to participate in this conversation.