0

We have 4 tables

  1. Users

    -id

  2. Profiles

    -id

    -user_id

  3. Questions

    -id

  4. Options

    -id

  5. ProfileQuestions

    -id

    -profile_id

    -question_id

    -option_id

Now i require to get all profiles and each profile have multiple questions and each question has many options.

User Model

    $this->hasMany('Profiles', [
      'foreignKey' => 'user_id'
    ]);

Profiles Model

     $this->belongsToMany('Questions', [
        'foreignKey' => 'profile_id',
        'targetForeignKey' => 'question_id',
        'joinTable' => 'profile_questions',
        'through' => 'ProfileQuestions'  ,
        'joinType' => 'LEFT']);

Questions Model

    $this->belongsToMany('Options', [
        'foreignKey' => ['question_id'],
        'targetForeignKey' => 'option_id',
        'joinTable' => 'profile_questions',
        'through' => 'ProfileQuestions'
    ]);

ProfileQuestions Model

     $this->belongsTo('Profile', [
        'foreignKey' => 'profile_id',
    ]);
    $this->belongsTo('Questions', [
        'foreignKey' => 'question_id'
    ]);
    $this->belongsTo('Options', [
        'foreignKey' => 'option_id'
    ]);

Controller code to get the result

     $query = $this->Users->find('first')
                $query->contain(['Profiles.Questions.Options']);

Error

    Fatal error: Out of memory (allocated 408944640) (tried to allocate 665912212 bytes) in vendor\cakephp\cakephp\src\Database\Statement\MysqlStatement.php on line 39

Issue is related to Associations. If we set the profile_id where condition with the options contain then it works for that profile id.

ndm
  • 59,784
  • 9
  • 71
  • 110
  • 1
    Possible duplicate of [Fatal error: Out of memory, but I do have plenty of memory (PHP)](https://stackoverflow.com/questions/12015569/fatal-error-out-of-memory-but-i-do-have-plenty-of-memory-php) – Balakrishnan Aug 03 '18 at 10:55
  • This is related to some issue in association. – Hitesh Jain Aug 03 '18 at 11:08
  • it might be helpful if you print and see the compiled SQL query https://stackoverflow.com/a/16808024/1464519 – Balakrishnan Aug 03 '18 at 11:14
  • `This is related to some issue in association.` - It obviously is not, the error message tells you why. I bet on that you simply fetch to much data and the memory is filled up. Read your data in chunks, problem solved. – floriank Aug 03 '18 at 16:05

0 Answers0