A
A
Anton Shelestov2020-11-16 19:16:55
Laravel
Anton Shelestov, 2020-11-16 19:16:55

Edit sql before database query?

Hello!
There is a working project on version 5.8
. Now we are doing a global update of the project, including laravel to the latest version.
In the latest version, it turns out that for convenience, everything was moved to the Models folder, it used to be in app/
And the corresponding namespace has changed a bit from App\User to App\Models\User.

And we have that polymorphic relations do not work. now there is a request to the model_type column with App\Models\User data, and everything is saved in the old database App\User.

Question: Is it possible to somehow edit this data before querying the database?
type: str_replace('\Models', '', $className)

And then, when the project is completed and ready for public, update the information in the database so that it is as it should be.

Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jazzus, 2020-11-16
@jazzus

Nothing prevents you from leaving the App\User model,
just new ones will be generated in models
or DB::table('table')->update(['model_type' => 'App\Models\User'])

P
pLavrenov, 2020-11-17
@pLavrenov

This should have been taken care of in the first place.
In general, there is an easy solution to the problem by adding the AppServiceProvider::register() method:

Relation::morphMap([
    'model' => Model::class,
]);

Where model is the name that was before (App\Models\User) and model is the model itself, but I faced some problems when I needed to get this name:
For example:
public function account()
{
    return $this->belongsTo(Account::class, 'target_id')->where('target_type', Account::$morphClass);
}

I began to add the name directly to the model: and it turns out like this:
public static $morphClass = 'account';
Relation::morphMap([
    Model::$morphClass => Model::class,
]);

Link to documentation
In general, for now, you can specify the name that was, but as the update progresses, it is better to replace these names in the database as well, because long names simply take up more space.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question