shakil
February 15, 2017, 10:37am
1
I have a table Users that has many Questions. For ex.:
UsersTable:
id, name, email
QuestionsTable:
id, user_id, question
When i use find query using UsersTable that “contain” Questions, then it doesn’t make any join in SQL.
But when i use find query using QuestionsTable that “contain” Users, then does join and builds sql as required.
I don’t understand why?
My query is:
$UsersTable = TableRegistry::get(‘Users’);
$user_questions = $UsersTable ->find(‘all’ , [ ‘conditions’ => [‘Users.id ’ => 1] ]) ->contain([‘Questions’]);
Regards.
fheider
February 15, 2017, 12:29pm
2
You have to defined 2 associations:
Users => hasMany Questions
Questions => belongsTo Users
shakil:
I don’t understand why?
It will be necessary to see your relationship configuration in the UsersTable initialize.
The documentation is very weak, I resolved a bunch of these types of problems by just messing around with those settings and refreshing my browser a lot.
The query you have defined should return the Users record with ID of one, and I assume you have a hasMany relationship to Questions, so all the questions with Questions.user_id = 1 returned in an array. Is that what you want?
shakil
February 27, 2017, 10:24am
4
Thank you for your response.
It is now working as required. Yes, I was needed to fetch all questions of a user with specific user id.
The associations in Tables was already properly built up like:
Users => hasMany Questions
Questions => belongsTo Users
Documentation for Cakephp 3.x is not so proper as in cakephp 2.x which creates trouble to understand.
in your usertable.php page write that code
public function initialize(array $config) {
parent::initialize($config);
$this->table('user_table_name');
$this->displayField('id');
$this->primaryKey('id');
$this->hasMany('Questions', [
'foreignKey' => 'user_id',
'joinType' => 'LEFT'
]);
}
In Questiontable.php write down that code
public function initialize(array $config) {
parent::initialize($config);
$this->table('question_table_name');
$this->displayField('id');
$this->primaryKey('id');
$this->belongsTo('User', [
'foreignKey' => 'user_id',
'joinType' => 'LEFT'
]);
}
I think it’s better example
I have used two tables with relation as below
$this->hasMany(‘Images’, [
‘foreignKey’ => ‘user_id’
]);
$this->belongsTo('Users', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
Used field in user add.ctp
echo $this->Form->control(‘images.file’);
image not saved ti image table.Provide solution to save multiple images to image table.
Hi,
Am unable to solve hasMany with contain problem. My Query is not concatenated with join. Pls Help…