Bake\Shell\Task\ModelTask::findBelongsTo PHP Method

findBelongsTo() public method

Find belongsTo relations and add them to the associations list.
public findBelongsTo ( Table $model, array $associations ) : array
$model Cake\ORM\Table Database\Table instance of table being generated.
$associations array Array of in progress associations
return array Associations with belongsTo added in.
    public function findBelongsTo($model, array $associations)
    {
        $schema = $model->schema();
        foreach ($schema->columns() as $fieldName) {
            if (!preg_match('/^.+_id$/', $fieldName)) {
                continue;
            }
            if ($fieldName === 'parent_id') {
                $className = $this->plugin ? $this->plugin . '.' . $model->alias() : $model->alias();
                $assoc = ['alias' => 'Parent' . $model->alias(), 'className' => $className, 'foreignKey' => $fieldName];
            } else {
                $tmpModelName = $this->_modelNameFromKey($fieldName);
                if (!in_array(Inflector::tableize($tmpModelName), $this->_tables)) {
                    $found = $this->findTableReferencedBy($schema, $fieldName);
                    if ($found) {
                        $tmpModelName = Inflector::camelize($found);
                    }
                }
                $assoc = ['alias' => $tmpModelName, 'foreignKey' => $fieldName];
                if ($schema->column($fieldName)['null'] === false) {
                    $assoc['joinType'] = 'INNER';
                }
            }
            if ($this->plugin && empty($assoc['className'])) {
                $assoc['className'] = $this->plugin . '.' . $assoc['alias'];
            }
            $associations['belongsTo'][] = $assoc;
        }
        return $associations;
    }

Usage Example

Ejemplo n.º 1
0
 /**
  * Test that belongsTo generation ignores _id mid-column
  *
  * @return void
  */
 public function testBelongsToGenerationIdMidColumn()
 {
     $model = TableRegistry::get('Articles');
     $model->schema(['id' => ['type' => 'integer'], 'thing_id_field' => ['type' => 'integer']]);
     $result = $this->Task->findBelongsTo($model, []);
     $this->assertEquals([], $result);
 }