Just add this to your model
/**
* The relations to eager load on every query.
*
* @var array
*/
protected $with = ['history'];
Hello!
I am trying to make a history of model saves so the previous versions can always be accessed... even with relations by another model. Its becoming a bit tricky and i hope you guys can help me out on logic and some other stuff.
For example. User creates an Act, adds some products to it and saves it. Then admin deletes couple of products or changes their values. Now, when user starts to process saved Act (when using regular delete, some products are missing or changed), he can see products he added (and can see notification that they are updated or removed) and can do whatever with this Act. But, he cannot add those deleted products to a new act.
Same thing with viewing old Acts that have long ago deleted products.
Also, this history trait should work with a lot other models too, so, basicly, almost everything has previous versions.
My logic was this: This needs to be a trait that i can add to different models. Make a model soft deletable and add a serial field to db table. When user updates model, it takes a serial id for that model and soft deletes the model. Then it creates a new one based on data and adds the same serial field value as soft deleted one has. So, all previous versions are soft deleted and the latest, active one, is not.
Then, whenever needed, i could take soft deleted models and display them or make a new model with deleted one's data (restoring previous save).
What you think of this logic?
The problem i encountered was retrieving the soft deleted values for certain model with relations like this:
$product = Product::with('history')->find(468);
This did not work (i figured as much as there are no foreign keys)
public function history() {
$class = get_class($this);
$this->HasMany($class,'serial','serial');
}
This did work but i would like to not be forced to use history command every time, i would very much prefer so it would always be there.
$product = Product::find(468);
$history = $product->history(); //this should be done behind the scenes
public function history() {
$serial = $this->serial;
$table = $this->getTable();
return DB::table($table)->where('serial',$serial)->where('deleted_at','!=','null')->get();
}
How can i have model to always load history?
Please or to participate in this conversation.