You are here

function farm_constraint_table_references in farmOS 7

Helper function for finding references to entities in tables.

Parameters

$references: An array of information about entity references. For example: $references = array( 'herd' => array( 'type' => 'farm_asset', 'bundle' => 'group', 'tables' => array( 'farm_grazing_rotations' => 'herd_id', 'farm_grazing_herds' => 'herd_id', ), ), );

$type: The entity type.

$bundle: The entity bundle.

$id: The entity ID.

Return value

array Returns an array of matching records.

2 calls to farm_constraint_table_references()
farm_constraint_table_references_exist in modules/farm/farm_constraint/farm_constraint.module
Helper function for checking to see if an entity reference exists in a database table.
farm_plan_farm_constraint in modules/farm/farm_plan/farm_plan.farm_constraint.inc
Implements hook_farm_constraint().

File

modules/farm/farm_constraint/farm_constraint.module, line 123
Farm constraint module.

Code

function farm_constraint_table_references($references, $type, $bundle, $id) {

  // Start an empty records array.
  $records = array();

  // Iterate through the references.
  foreach ($references as $info) {

    // If the entity type doesn't match, skip it.
    if ($type != $info['type']) {
      continue;
    }

    // If a the referenced bundle matters, check it.
    if (!empty($info['bundle']) && $bundle != $info['bundle']) {
      continue;
    }

    // If there is no table information defined, skip it.
    if (empty($info['tables'])) {
      continue;
    }

    // Iterate through the tables.
    foreach ($info['tables'] as $table => $column) {

      // Query for a matching entity reference in the table.
      $exists = db_query('SELECT COUNT(*) FROM {' . $table . '} WHERE ' . $column . ' = :id', array(
        ':id' => $id,
      ))
        ->fetchField();

      // If one exists, a constraint exists. Return TRUE.
      if (!empty($exists)) {
        $records[] = array(
          'constraint' => 'table_reference',
          'table' => $table,
          'column' => $column,
          'entity_type' => $type,
          'entity_id' => $id,
        );
      }
    }
  }

  // Return matching records.
  return $records;
}