HasMany association does not work well when usingDbConfig is changed in the model

Asked 2 years ago, Updated 2 years ago, 50 views

After switching databases, some of the $hasMany associated parts of the retrieved data are not linked.

<Table>

  • posts table
  • tags table
  • posts_tags table (intermediate table)

  • post.php
  • tag.php
  • posts_tag.php($name='PostsTag')

  • Development Environment ('development')
  • Test Environment ('testDb')

ddatabase.php is omitted

After switching db, the retrieved data is not captured correctly.
Please see below.
$hasmany PostsTag, an intermediate table model, in the post model.
The PostsTag of $data obtained at this time can capture the PostsTag model data...
Sub-defined ?[PostsTag_Sub] does not contain PostsTag model data!!!

By the way, if you don't switch db, all the data will be taken correctly.

I'm in trouble.Please let me know.

//post.php

class Post extensions AppModel
{

    public$hasMany=[
        'PostsTag',
        'PostsTag_Sub' = > [
            'className' = > 'PostsTag',
        ],
    ];

    public function getData()
    {
        // In the development
        $oldDb=$this->Tag->useDbConfig;//development
        // Switch to test environment (testDb).
        $database='testDb';
        $this->dbChange($database);
        // Data Retrieval
        $data = $this->find('all');
        print_r($data);
    }    
    // Database switching process
    public function dbChange ($database)
    {
         $this->useDbConfig=$database;
         $this->tag->useDbConfig=$database;
         $this->posts_tag->useDbConfig=$database;
     }
}

php cakephp

2022-09-30 16:59

1 Answers

In this case, it seems that PostsTag and PostsTag_Sub are different instances even in the same class, so DbConfig should also be changed for PostsTag_Sub.

public function dbChange ($database)
{
    $this->useDbConfig=$database;
    $this->PostsTag->useDbConfig=$database;
    $this->PostsTag_Sub->useDbConfig=$database;
}

*I only guessed from the code and manual written in the question, so I have not checked the operation


2022-09-30 16:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.