Astrotomic / laravel-translatable

A Laravel package for multilingual models
https://docs.astrotomic.info/laravel-translatable/
MIT License
1.23k stars 156 forks source link

How To Update Model TimeStamps #259

Closed boranbar closed 2 years ago

boranbar commented 2 years ago

Hello,

First of all, thank you for this great package.

I have a question about timestamps.

So let's assume we have posts and post_translations table.

According to the docs, there is no created_at and updated_at columns on translation table.

I realized that, if i update some record in post_translations table, my main posts table's updated_at column is not changing.

If one of the columns in my post_translations table is updated, I want the updated_at column of my main table to be also updated.

How can i achieve that?

Thanks for the help.

boranbar commented 2 years ago

UPDATE Here is the solution;

In our PostTranslation model, all we have to do define a belongsTo relation and use Elequent touch.

protected $touches = ['post'];

public function post(): BelongsTo
    {
        return $this->belongsTo(Post::class);
    }
ahbanavi commented 1 year ago

@boranbar FYI, Your solution doesn't work if lazy loading is disabled.

UPDATE for anyone coming to this from google, I was able to solve this problem by doing something like this:

        Model::handleLazyLoadingViolationUsing(function (Model $model, string $relation): void {
            $model_name = class_basename($model);

            // if model name ends with Translation and relation is the model name without Translation, allow
            if (Str::endsWith($model_name, 'Translation') && $relation === Str::camel(Str::replaceLast('Translation', '', $model_name))) {
                return;
            }

            throw new LazyLoadingViolationException($model, $relation);
        });