Example #1
0
 /**
  * Join on middle table of a many-to-many relation.
  *
  * @param ManyMany $rel The relation.
  * @param string   $cmAlias The current model alias.
  * @param int      $joinType
  */
 protected function _addJoinClauseManyMany(ManyMany $rel, $cmAlias, $joinType)
 {
     // $md stands for "middle".
     $mdTable = $rel->getMiddleTableName();
     $mdAlias = $rel->getMiddleTableAlias();
     $mdAlias = $cmAlias === self::DEFAULT_ROOT_ALIAS ? $mdAlias : $cmAlias . '.' . $mdAlias;
     $jcMiddle = new JoinClause($mdTable, $mdAlias, $joinType);
     $jcMiddle->on($cmAlias, $rel->cm->column, $mdAlias, $rel->jm->from);
     $this->setJoinClause($mdAlias, $jcMiddle);
     return $mdAlias;
 }
 public function testWhereRelation()
 {
     $b = new WhereBuilder();
     $b->root('Article', 'articles');
     $b->whereRelation(Blog::relation('articles'), '_');
     $components = $b->build();
     $where[] = ['type' => 'Attribute', 'lTable' => 'articles', 'lCols' => ['blog_id'], 'op' => '=', 'rTable' => '_', 'rCols' => ['id'], 'logic' => 'AND'];
     $this->assertEquals($where, $components['where']);
     $this->assertEquals(Blog::table(), $b->getInvolvedTable('_'));
     // - - -
     // With many-to-many relation.
     $rel = Article::relation('readers');
     $mdName = $rel->getMiddleTableName();
     $mdAlias = $rel->getMiddleTableAlias();
     $b = new WhereBuilder();
     $b->root('User', 'readers');
     $b->whereRelation($rel, '_');
     $components = $b->build();
     $jc = new JoinClause($mdName, $mdAlias);
     $jc->on('readers', 'id', $mdAlias, 'user_id');
     $where = [['type' => 'Attribute', 'lTable' => $mdAlias, 'lCols' => ['article_id'], 'op' => '=', 'rTable' => '_', 'rCols' => ['id'], 'logic' => 'AND']];
     $this->assertEquals($where, $components['where']);
     $this->assertEquals(Article::table(), $b->getInvolvedTable('_'));
     $this->assertEquals($jc, $b->getJoinClause($mdAlias));
     try {
         $b->getJoinClause('_');
         $this->fail('Should have thrown an exception.');
     } catch (Exception $ex) {
         $this->assertContains('_', $ex->getMessage());
     }
 }