首页 > 解决方案 > 如何使用 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;
}

}

标签: cakephp

解决方案


将您的关系更改为以下内容:

$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

推荐阅读