3

I want to select data of questions from quizdetails table. And data of questions will be join with answers table, too. So I using code php:

$questions = $this
    ->QuizDetails->find()
    ->contain([
        'Questions' => function($q) {
            return $q->contain(['Answers']);
        }
    ])
    ->where(['QuizDetails.quiz_id' => $id]);

file AnswersTable:

$this->table('answers');
$this->belongsTo('Questions', [
    'className' => 'Publishing.Questions',
    'foreignKey' => 'question_id',
]);

file QuizDetailsTable:

$this->table('quiz_details');
$this->belongsTo('Questions', [
    'className' => 'Publishing.Questions',
    'foreignKey' => 'question_id',
]);

So, when i run it, through a error Questions is not associated with Answers

If I using:

$question = $this->Questions->find()->contain(['Answers'])

That is ok. Please help me to fix it.

Danila Ganchar
  • 10,266
  • 13
  • 49
  • 75
Hùng KaKa
  • 31
  • 2

4 Answers4

0

If I am not wrong you just need to contain Questions and Answers within QuizDetails , if so simply try:

$questions = $this->QuizDetails->find()->contain(['Questions.Answers'])
             ->where(['QuizDetails.quiz_id' => $id]);
Manohar Khadka
  • 2,186
  • 2
  • 18
  • 30
0

Because of two tables are not assosiated. You should define the condition to connect.

$this->belongsTo('Questions', [
        'className' => 'Publishing.Questions',
        'conditions' => ['A.id' => 'B.id'], //add this
]);

P/s: I'm ad form FB Cakephp Viet who answer your posted question in there.

TommyDo
  • 663
  • 8
  • 23
0

problem from: 'className' => 'Publishing.Questions' And I change file QuizDetailsTable to:

$this->table('quiz_details');
$this->belongsTo('Questions', [
        'className' => 'Publishing.Questions',
        'foreignKey' => 'question_id'
]);

That is OK

Thanks all

Hùng KaKa
  • 31
  • 2
0

you have to define both ways.

this ...

$this->table('answers');
$this->belongsTo('Questions', [
    'className' => 'Publishing.Questions',
    'foreignKey' => 'question_id',
]);

... and this:

$this->table('question');
$this->hasMany('Answers', [
    'className' => 'Publishing.Answers',
    'foreignKey' => 'question_id',
]);

In your example you only can do this:

$answer = $this->Answers->find()->contain(['Questions']);
George Moik
  • 445
  • 4
  • 10