Reputation: 85
I have two Table Class:
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use App\Model\Entity\Comlib;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Validator;
use Cake\ORM\TableRegistry;
class ComlibsTable extends Table {
public function initialize(array $config) {
parent::initialize($config);
$this->table('questions');
// JOIN THE TABLES TOMORROW
$this->hasMany('Answers' , [
'foreignKey' => 'question_id'
]);
}
public function LFM( $live_req) {
$answers = TableRegistry::get('questions');
$query = $answers->find()
->distinct(['question.id'])
->matching('Answers', function ($q) use ($options) {
return $q->where(['Answers.id IN'=> '1']);
});
$query = $query->all();
//want Answers five of then
return $query;
}
}
?>
the 2nd Table :
use Cake\ORM\Table;
use Cake\ORM\Query;
use Cake\ORM\TableRegistry;
class AnswersTable extends Table {
public function initialize(array $config) {
parent::initialize($config);
$this->table('answers');
}
}
In the database I have a question table and answer table, answer table has a foreign key named : question_id. What I want to do is I want to select everything from question and join it with answers via id , possible innerjoin and the error I get is:
questions is not associated with answers
Any help would be appreciated.
Upvotes: 1
Views: 757
Reputation: 9398
You're confusing the table in your database with cakePHP Table
class
when you call TableRegistry::get()
you have to pass the name of the Table class. So the right syntax would be
$answers = TableRegistry::get('Comlibs');
and cake will instantiate a new object of ComlibsTable
Class
Anyway you don't even need to do this because you're already inside the ComlibsTable and you can use $this
to reference the Table. So all you have to do is
$query = $this->find()
->distinct(['question.id'])
->matching('Answers', function ($q) use ($options) {
return $q->where(['Answers.id IN'=> '1']);
})
->all();
Upvotes: 1