mardi 1 août 2017

Laravel touching (recursive)

Question: how to touch a model from the same model?

Details: I'm using Laravel 5.4 to build an application for renting books between people. In each transaction there are 2 parts: information concerning the owner VS information concerning the person who is renting the book.

Because the the 2 sides, I chose to use only one table named rents for both sides. To distinguish which is which I added a field rent_side that contains 'owner' or 'borrower'. This makes it easy if I want to show/search a history of a person. If had 2 ore more tables, I would have to make a UNION to select all the data needed to show the history.

These two sides are coupled together thanks to common id called couple_id.

From each side, I can see the opposed side thanks to method located in the model App\Rent I named reverse, where I do the following:

public function reverse()
{
    return $this->hasOne('App\Rent', 'couple_id', 'couple_id')
        ->where('id', '!=', $this->id);
}

Because I need to update the parent timestaps and according to laravel documentation I used the following:

protected $touches = ['reverse'];

The problem is that this touching affects the same model. So when I update/insert a new record, the request takes up to 4min before sending an error. As if it went into an endless loop.

Is there a way to touch a model from the same model?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire