我有一个评论表,用户可以这样评论另一个用户:
以下是限制条件:
当我使用这个查询时:
$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;
}
}
发布于 2018-08-23 01:09:12
把你的人际关系改成这样:
$this->belongsTo('Commenters', [
'className' => 'Users',
'foreignKey' => 'commentator_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Users', [
'foreignKey' => 'commented_id',
'joinType' => 'INNER'
]);
因此,您可以包含这两种不同的关系。
$comments = TableRegistry::getTableLocator()
->get('Comments')
->find('all')
->contain(['Commenters', 'Users']);
并像这样访问它们:
$comment->commenter->name; // Name of the person who commented
$comment->user->name; // Name of the person who was commented on
发布于 2018-08-20 00:44:28
我不确定输出的确切内容是什么,但据我所知,您可以使用自定义连接来实现同样的效果:
$data = $this->Comments->find()
->join([
'Users' => [
'table' => 'users',
'type' => 'INNER',
'conditions' => [
'Users.id=Comments.commentator_id',
'OR' => [
'Users.id=Comments.commented_id'
]
]
]
]);
或者您可以根据需要对其进行修改。
https://book.cakephp.org/3.0/en/orm/query-builder.html#adding-joins
希望这能有所帮助。
https://stackoverflow.com/questions/51919010
复制相似问题