我有一个评论表,用户可以这样评论另一个用户:
以下是限制条件:
当我使用这个查询时:
$comments = TableRegistry::getTableLocator()
->get('Comments')
->find('all');
$query = $comments
->find('all')
->contain(['Users']);
它检索注释,但在 commented_id上应用join only 。虽然我希望检索包含的注释对象,但它的两个相关用户一个是评论员,另一个是注释用户,那么如何构建查询呢?
这是CommentsTable:
class CommentsTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('comments');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->belongsTo('Users', [
'foreignKey' => 'commentator_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Users', [
'foreignKey' => 'commented_id',
'joinType' => 'INNER'
]);
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmpty('id', 'create');
$validator
->scalar('content')
->maxLength('content', 255)
->requirePresence('content', 'create')
->notEmpty('content');
$validator
->integer('score')
->requirePresence('score', 'create')
->notEmpty('score');
$validator
->dateTime('created_at')
->requirePresence('created_at', 'create')
->notEmpty('created_at');
$validator
->dateTime('updated_at')
->requirePresence('updated_at', 'create')
->notEmpty('updated_at');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['commentator_id'], 'Users'));
$rules->add($rules->existsIn(['commented_id'], 'Users'));
return $rules;
}
}
https://stackoverflow.com/questions/51919010
复制相似问题