kc_
kc_

Reputation: 11

Yii2, few tables with uncomfortable generic field names for 1 Model

I'm building REST++ service with Yii2, which should be able to deal with 2 table schemes, (databases storing ~the~same~ data):

  1. a_new_one, which is perfect to be handled with ActiveRecord;
  2. the_old_one, which has 1 generic table 'Object' with columns like 'field1', 'field2', etc, and few additional tables.

I want my request methods and controllers to be all the same for both schemes (would be very great, really). That means, that I need to have THE SAME MODELS for both cases.

The troubles all relate to the_old_one database: Let's say data of model User is stored in tables Object and UserProfile. If I make 2 ActiveRecord classes for both tables, will it be possible to make hasOne() relations to them in 3d class User (not sure about inheritance here), so it can be manipulated like this:

$user = User::find()->someFilters()->someOrderingAndPagination()->one();
$user->Name = $your_new_name;
$user->Age = $why_not_90;
$user->save();
// and so on.

Because I really don't want to be forced to write it like this:

$user = User::find()->notSureAboutRelations()
    ->filters()->ordering()->pagination()->one();
$user->object->field7 = $your_new_name;
$user->userProfile->Age = $why_not_90;
$user->save();

I learned, Doctrine has easy model mapping ($user->Name can be mapped to db's Object.field7), but it's still impossible to map to 2 different tables within 1 Entity. Or am I incorrect ? If so, would it be a good idea to use Doctrine within Yii2 ?

Upvotes: 1

Views: 67

Answers (1)

kc_
kc_

Reputation: 11

So finished with idea to have the same controllers and models. Only URLs remain the same.

The old db Model data could be gained this way:

$user = User::find()
  ->select([
    'Object.field7 as Name',
    'UserProfile.Age as Age',
    // ...
  ])->from('Object')
  ->join('UserProfile', ['UserProfile.ObjectId = Object.Id'])
  ->andWhere('User.Id' => $id);

And it's an ugly mess up when saving this models. Cos you need to assign a lot of fields in BEFORE_INSERT, BEFORE_UPDATE events.

Upvotes: 0

Related Questions