Bake\Shell\Task\ModelTask::findBelongsToMany PHP Метод

findBelongsToMany() публичный Метод

Find the BelongsToMany relations and add them to associations list
public findBelongsToMany ( Table $model, array $associations ) : array
$model Cake\ORM\Table Model instance being generated
$associations array Array of in-progress associations
Результат array Associations with belongsToMany added in.
    public function findBelongsToMany($model, array $associations)
    {
        $schema = $model->schema();
        $tableName = $schema->name();
        $foreignKey = $this->_modelKey($tableName);
        $tables = $this->listAll();
        foreach ($tables as $otherTableName) {
            $assocTable = null;
            $offset = strpos($otherTableName, $tableName . '_');
            $otherOffset = strpos($otherTableName, '_' . $tableName);
            if ($offset !== false) {
                $assocTable = substr($otherTableName, strlen($tableName . '_'));
            } elseif ($otherOffset !== false) {
                $assocTable = substr($otherTableName, 0, $otherOffset);
            }
            if ($assocTable && in_array($assocTable, $tables)) {
                $habtmName = $this->_camelize($assocTable);
                $assoc = ['alias' => $habtmName, 'foreignKey' => $foreignKey, 'targetForeignKey' => $this->_modelKey($habtmName), 'joinTable' => $otherTableName];
                if ($assoc && $this->plugin) {
                    $assoc['className'] = $this->plugin . '.' . $assoc['alias'];
                }
                $associations['belongsToMany'][] = $assoc;
            }
        }
        return $associations;
    }

Usage Example

Пример #1
0
 /**
  * Test that HABTM generation works
  *
  * @return void
  */
 public function testHasAndBelongsToManyGeneration()
 {
     $this->Task->connection = 'test';
     $model = TableRegistry::get('BakeArticles');
     $result = $this->Task->findBelongsToMany($model, []);
     $expected = ['belongsToMany' => [['alias' => 'BakeTags', 'foreignKey' => 'bake_article_id', 'joinTable' => 'bake_articles_bake_tags', 'targetForeignKey' => 'bake_tag_id']]];
     $this->assertEquals($expected, $result);
 }