cakephp - 如何使用 Cakephp 进行查询连接?
问题描述
当我使用此查询时:
$comments = TableRegistry::getTableLocator()
->get('Comments')
->find('all');
$query = $comments
->find('all')
->contain(['Users']);
它检索评论,但仅在commented_id上应用联接。虽然我想检索包含两个相关用户的评论对象,一个作为评论者,另一个作为评论者,;那么如何构建查询呢?
这是评论表:
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;
}
}
解决方案
将您的关系更改为以下内容:
$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
推荐阅读
- javascript - 从函数输出中读取属性
- javascript - D3 Uncaught TypeError:无法读取未定义的属性“年龄”
- python - VS Code:告诉 pylint 忽略下一行?
- swift - 选择“使用应用程序时”时,CLLocationManager 不起作用
- javascript - javascript while循环使用函数式编程和异步
- java - 动态删除 Java Swing 容器(我的代码在按钮按下时挂起)
- google-sheets-api - 谷歌表外部网络应用程序使用密钥进行身份验证失败
- html - 响应式图像幻灯片
- 和
- sh - 如何设置 rc.d 脚本以在 FreeBSD 中启动 Plex 媒体服务器?
- node.js - 如何将凭据传递给我的数据库连接类?