protected static function generateCampaignItems($campaign, $pageSize) { if ($pageSize == null) { $pageSize = self::DEFAULT_CAMPAIGNITEMS_TO_CREATE_PAGE_SIZE; } $contacts = array(); $quote = DatabaseCompatibilityUtil::getQuote(); $marketingListMemberTableName = RedBeanModel::getTableName('MarketingListMember'); $campaignItemTableName = RedBeanModel::getTableName('CampaignItem'); $sql = "select {$quote}{$marketingListMemberTableName}{$quote}.{$quote}contact_id{$quote} from {$quote}{$marketingListMemberTableName}{$quote}"; // Not Coding Standard $sql .= "left join {$quote}{$campaignItemTableName}{$quote} on "; $sql .= "{$quote}{$campaignItemTableName}{$quote}.{$quote}contact_id{$quote} "; $sql .= "= {$quote}{$marketingListMemberTableName}{$quote}.{$quote}contact_id{$quote}"; $sql .= "AND {$quote}{$campaignItemTableName}{$quote}.{$quote}campaign_id{$quote} = " . $campaign->id . " "; $sql .= "where {$quote}{$marketingListMemberTableName}{$quote}.{$quote}marketinglist_id{$quote} = " . $campaign->marketingList->id; $sql .= " and {$quote}{$campaignItemTableName}{$quote}.{$quote}id{$quote} is null limit " . $pageSize; $ids = R::getCol($sql); foreach ($ids as $contactId) { $contacts[] = Contact::getById((int) $contactId); } if (!empty($contacts)) { //todo: if the return value is false, then we might need to catch that since it didn't go well. CampaignItem::registerCampaignItemsByCampaign($campaign, $contacts); if (count($ids) < $pageSize) { return true; } } else { return true; } return false; }
/** * @param @modelClassName - the main 'from part' table is this model's table. This is considered the base table */ public function __construct($modelClassName) { assert('is_string($modelClassName)'); $tableName = RedBeanModel::getTableName($modelClassName); $quote = DatabaseCompatibilityUtil::getQuote(); $this->baseFromTableName = $tableName; $this->addTableCount($tableName); }
/** * Constructs a new RedBeanModels which is a collection of classes extending model. * The models are created lazily. * Models are only constructed with beans by the model. Beans are * never used by the application directly. */ public function __construct(RedBean_OODBBean $bean, $modelClassName) { assert('is_string($modelClassName)'); assert('$modelClassName != ""'); $this->modelClassName = $modelClassName; $tableName = RedBeanModel::getTableName($modelClassName); $this->bean = $bean; $this->relatedBeansAndModels = array_values(R::related($this->bean, $tableName)); }
/** * For a give User name, run a partial search by * full name and retrieve user models. * */ public static function getUsersByPartialFullName($partialName, $pageSize) { assert('is_string($partialName)'); assert('is_int($pageSize)'); $personTableName = RedBeanModel::getTableName('Person'); $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter('User'); $joinTablesAdapter->addFromTableAndGetAliasName($personTableName, "{$personTableName}_id"); $fullNameSql = DatabaseCompatibilityUtil::concat(array('person.firstname', '\' \'', 'person.lastname')); $where = " (person.firstname like lower('{$partialName}%') or " . " person.lastname like lower('{$partialName}%') or " . " {$fullNameSql} like lower('{$partialName}%')) "; return User::getSubset($joinTablesAdapter, null, $pageSize, $where, "person.firstname, person.lastname"); }
public static function getModelsByFullName($modelClassName, $fullName) { assert('is_string($modelClassName)'); assert('is_subclass_of($modelClassName, "Person") && $modelClassName != "Person" ||' . '$modelClassName == "User"'); assert('is_string($fullName)'); $personTableName = RedBeanModel::getTableName('Person'); $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter($modelClassName); $joinTablesAdapter->addFromTableAndGetAliasName($personTableName, "{$personTableName}_id"); $fullNameSql = DatabaseCompatibilityUtil::concat(array('person.firstname', '\' \'', 'person.lastname')); $where = "{$fullNameSql} = '{$fullName}'"; return $modelClassName::getSubset($joinTablesAdapter, null, null, $where); }
/** * Given a model class name, return all the derived attributes based on the called class. * @param string $modelClassName */ public static function getAllByModelClassName($modelClassName) { assert('$modelClassName != ""'); $derivedAttirbuteMetadataTableName = RedBeanModel::getTableName('DerivedAttributeMetadata'); $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter(get_called_class()); $joinTablesAdapter->addFromTableAndGetAliasName($derivedAttirbuteMetadataTableName, "{$derivedAttirbuteMetadataTableName}_id"); $where = "{$derivedAttirbuteMetadataTableName}.modelclassname = '{$modelClassName}'"; $models = static::getSubset($joinTablesAdapter, null, null, $where); if (count($models) == 0) { return array(); } return $models; }
public static function updateValueByDataIdAndOldValueAndNewValue($customFieldDataId, $oldValue, $newValue) { $quote = DatabaseCompatibilityUtil::getQuote(); $customFieldTableName = RedBeanModel::getTableName('CustomField'); $baseCustomFieldTableName = RedBeanModel::getTableName('BaseCustomField'); $baseCustomFieldJoinColumnName = $baseCustomFieldTableName . '_id'; $valueAttributeColumnName = 'value'; $dataAttributeColumnName = RedBeanModel::getForeignKeyName('BaseCustomField', 'data'); $sql = "update {$quote}{$customFieldTableName}{$quote}, {$quote}{$baseCustomFieldTableName}{$quote} "; $sql .= "set {$quote}{$valueAttributeColumnName}{$quote} = '{$newValue}' "; $sql .= "where {$quote}{$customFieldTableName}{$quote}.{$baseCustomFieldJoinColumnName} = "; // Not Coding Standard $sql .= "{$quote}{$baseCustomFieldTableName}{$quote}.id "; $sql .= "AND {$quote}{$dataAttributeColumnName}{$quote} = {$customFieldDataId} "; $sql .= "AND {$quote}{$valueAttributeColumnName}{$quote} = '{$oldValue}'"; R::exec($sql); }
public static function getByLayoutIdAndUser($layoutId, $user) { assert('is_integer($layoutId) && $layoutId >= 1'); assert('$user instanceof User && $user->id > 0'); $sql = 'select dashboard.id id ' . 'from dashboard, ownedsecurableitem ' . 'where ownedsecurableitem.owner__user_id = ' . $user->id . ' and dashboard.ownedsecurableitem_id = ownedsecurableitem.id ' . ' and layoutid = ' . $layoutId . ' order by layoutId;'; $ids = R::getCol($sql); assert('count($ids) <= 1'); if (count($ids) == 0) { if ($layoutId == Dashboard::DEFAULT_USER_LAYOUT_ID) { return Dashboard::setDefaultDashboardForUser($user); } throw new NotFoundException(); } $bean = R::load(RedBeanModel::getTableName('Dashboard'), $ids[0]); assert('$bean === false || $bean instanceof RedBean_OODBBean'); if ($bean === false) { throw new NotFoundException(); } return self::makeModel($bean); }
/** * For a give Contact name, run a partial search by * full name and retrieve contact models. * */ public static function getContactsByPartialFullName($partialName, $pageSize, $stateMetadataAdapterClassName = null) { assert('is_string($partialName)'); assert('is_int($pageSize)'); assert('$stateMetadataAdapterClassName == null || is_string($stateMetadataAdapterClassName)'); $personTableName = RedBeanModel::getTableName('Person'); $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter('Contact'); if (!$joinTablesAdapter->isTableInFromTables('person')) { $joinTablesAdapter->addFromTableAndGetAliasName($personTableName, "{$personTableName}_id"); } $metadata = array('clauses' => array(), 'structure' => ''); if ($stateMetadataAdapterClassName != null) { $stateMetadataAdapter = new $stateMetadataAdapterClassName($metadata); $metadata = $stateMetadataAdapter->getAdaptedDataProviderMetadata(); $metadata['structure'] = '(' . $metadata['structure'] . ')'; } $where = RedBeanModelDataProvider::makeWhere('Contact', $metadata, $joinTablesAdapter); if ($where != null) { $where .= 'and'; } $where .= self::getWherePartForPartialNameSearchByPartialName($partialName); return Contact::getSubset($joinTablesAdapter, null, $pageSize, $where, "person.firstname, person.lastname"); }
/** * Constructs a new RedBeanModels which is a collection of classes extending model. * The models are created lazily. * Models are only constructed with beans by the model. Beans are * never used by the application directly. * The application can construct a new models object by constructing * them without specifying a bean. In other words, if Php had overloading * and friends the constructor without the $bean would be public, and the * constructor taking a bean would private and available only to RedBeanModel. */ public function __construct($modelClassName, $sqlOrBean = '') { assert('is_string($sqlOrBean) || $sqlOrBean instanceof RedBean_OODBBean'); $this->modelClassName = $modelClassName; $this->position = 0; $tableName = RedBeanModel::getTableName($modelClassName); if (is_string($sqlOrBean)) { $this->relatedBeansAndModels = array_values(R::find($tableName, $sqlOrBean)); } else { assert('$sqlOrBean instanceof RedBean_OODBBean'); $this->bean = $sqlOrBean; // I had this... // $this->relatedBeansAndModels = array_values(R::related($this->bean, $tableName)); // and the doco says to use related in place of findLinks which is deprecated, // but that is returning zero when I know there are linked beans. try { // So I'm getting them with the link manager, but that can // throw if the table or column doesn't exist yet because there // are no linked beans. if ($this->bean->id > 0) { $relatedIds = ZurmoRedBeanLinkManager::getKeys($this->bean, $tableName); $this->relatedBeansAndModels = array_values(R::batch($tableName, $relatedIds)); } else { $this->relatedBeansAndModels = array(); } } catch (RedBean_Exception_SQL $e) { // SQLSTATE[42S02]: Base table or view not found... // SQLSTATE[42S22]: Column not found... if (!in_array($e->getSQLState(), array('42S02', '42S22'))) { throw $e; } // If there is nothing yet linked // just have no related models yet. $this->relatedBeansAndModels = array(); } } }
/** * Query a model's table by attributeName to get the count of attribute values. * An example usage is if you want to know how many records have a certain contact state for all states. * @param $filterByAttributeName - string identifying attribute that should be filtered on. * @param $filterByAttributeValue - string of value to filter the attribute by. * @return array of atributeValue / count pairings. */ public static function getCountData($modelClassName, $attributeName, $filterByAttributeName = null, $filterByAttributeValue = null) { assert('($filterByAttributeName == null && $filterByAttributeValue == null) || ($filterByAttributeName != null && $filterByAttributeValue != null)'); $model = new $modelClassName(); $tableName = RedBeanModel::getTableName($modelClassName); $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter($modelClassName); $selectQueryAdapter = new RedBeanModelSelectQueryAdapter(); if ($model->isRelation($attributeName) && $model->getRelationType($attributeName) == RedBeanModel::HAS_MANY) { assert('$attributeName == "values"'); //until we expand support on this method. $relationModelClassName = $model->getRelationModelClassName($attributeName); $attributeTableName = RedBeanModel::getTableName($relationModelClassName); $columnName = 'value'; $relationTableAliasName = $joinTablesAdapter->addLeftTableAndGetAliasName($attributeTableName, 'id', $tableName, $tableName . '_id'); } else { $attributeTableName = $tableName; $columnName = $model->getColumnNameByAttribute($attributeName); } $where = null; if ($filterByAttributeName != null) { $attributeModelClassName = $model->resolveAttributeModelClassName($filterByAttributeName); $filterByAttributeTableName = RedBeanModel::getTableName($attributeModelClassName); $filterByColumnName = $model->getColumnNameByAttribute($filterByAttributeName); $where = $filterByAttributeTableName . '.' . $filterByColumnName . '=' . $filterByAttributeValue; if ($filterByAttributeTableName != $tableName) { $joinTablesAdapter->addFromTableAndGetAliasName($filterByAttributeTableName, $filterByAttributeTableName . '_id', $tableName); } } $where = $where; $selectDistinct = false; $selectQueryAdapter->addClause($attributeTableName, $columnName, 'attribute'); $selectQueryAdapter->addCountClause($tableName, 'id', 'count'); $groupBy = static::getGroupBySqlPart($attributeTableName, $columnName); $sql = SQLQueryUtil::makeQuery($tableName, $selectQueryAdapter, $joinTablesAdapter, null, null, $where, null, $groupBy); return static::runQueryBySqlAndGetCountData($sql); }
/** * Override of the parent method using RedBean. * @param $category * @param $languageCode * @return array */ protected function loadMessagesFromDb($category, $languageCode) { assert('is_string($category)'); assert('is_string($languageCode)'); $sourceTableName = RedBeanModel::getTableName('MessageSource'); $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter('MessageTranslation'); $joinTablesAdapter->addFromTableAndGetAliasName($sourceTableName, "{$sourceTableName}_id"); $where = " messagesource.`category` = '{$category}' AND" . " messagetranslation.`language` = '{$languageCode}' "; $beans = MessageTranslation::getSubset($joinTablesAdapter, null, null, $where); $messages = array(); foreach ($beans as $bean) { $messages[$bean->messagesource->source] = $bean->translation; } return $messages; }
/** * Given a related attribute on a model and the related attribute is a has_many relation, * build the join and where sql string information. * @param $onTableAliasName * @param $operatorType * @param $value * @param $where * @param $whereKey * @throws NotSupportedException */ protected function buildWhereForRelatedAttributeThatIsItselfAHasManyRelation($onTableAliasName, $operatorType, $value, &$where, $whereKey) { assert('is_string($onTableAliasName)'); assert('is_string($operatorType)'); assert('(is_array($value) && count($value) > 0) || is_string($value) || is_int($value)'); assert('is_array($where)'); assert('is_int($whereKey)'); if (!$this->modelAttributeToDataProviderAdapter->getRelatedAttributeRelationType() == RedBeanModel::HAS_MANY) { throw new NotSupportedException(); } $relationAttributeModelClassName = $this->modelAttributeToDataProviderAdapter->getRelatedAttributeRelationModelClassName(); if ($relationAttributeModelClassName != 'CustomFieldValue' && $operatorType != 'allOf') { $modelClassName = $this->modelAttributeToDataProviderAdapter->getRelationModelClassName(); $relationAttributeTableName = RedBeanModel::getTableName($modelClassName); $joinColumnName = $modelClassName::getColumnNameByAttribute($this->modelAttributeToDataProviderAdapter->getRelatedAttribute()); $relationColumnName = self::resolveForeignKey(RedBeanModel::getTableName($this->modelAttributeToDataProviderAdapter->getModelClassName())); } else { $relationAttributeTableName = RedBeanModel::getTableName($relationAttributeModelClassName); $joinColumnName = 'value'; $relationColumnName = self::resolveForeignKey(RedBeanModel::getTableName($this->modelAttributeToDataProviderAdapter->getRelatedAttributeModelClassName())); } $tableAliasName = $relationAttributeTableName; $quote = DatabaseCompatibilityUtil::getQuote(); $where[$whereKey] = "(1 = (select 1 from {$quote}{$relationAttributeTableName}{$quote} {$tableAliasName} " . "where {$quote}{$tableAliasName}{$quote}.{$quote}{$relationColumnName}{$quote} = " . "{$quote}{$onTableAliasName}{$quote}.id " . "and {$quote}{$tableAliasName}{$quote}.{$quote}{$joinColumnName}{$quote} " . DatabaseCompatibilityUtil::getOperatorAndValueWherePart($operatorType, $value) . " limit 1))"; }
protected static function getMainTableName($modelClassName) { assert('is_string($modelClassName) && $modelClassName != ""'); return RedBeanModel::getTableName($modelClassName); }
/** * @depends testAutoBuildDatabase */ public function testAutoBuildUpgrade() { $this->unfreezeWhenDone = false; if (RedBeanDatabase::isFrozen()) { RedBeanDatabase::unfreeze(); $this->unfreezeWhenDone = true; } // adding Text Field $metadata = Account::getMetadata(); $metadata['Account']['members'][] = 'newField'; $rules = array('newField', 'type', 'type' => 'string'); $metadata['Account']['rules'][] = $rules; $metadata['Account']['members'][] = 'string128'; $rules = array('string128', 'type', 'type' => 'string'); $metadata['Account']['rules'][] = $rules; $rules = array('string128', 'length', 'min' => 3, 'max' => 128); $metadata['Account']['rules'][] = $rules; $metadata['Account']['members'][] = 'string555'; $rules = array('string555', 'type', 'type' => 'string'); $metadata['Account']['rules'][] = $rules; $rules = array('string555', 'length', 'min' => 1, 'max' => 555); $metadata['Account']['rules'][] = $rules; $metadata['Account']['members'][] = 'string100000'; $rules = array('string100000', 'type', 'type' => 'string'); $metadata['Account']['rules'][] = $rules; $rules = array('string100000', 'length', 'min' => 1, 'max' => 100000); $metadata['Account']['rules'][] = $rules; $metadata['Account']['members'][] = 'textField'; $rules = array('textField', 'type', 'type' => 'text'); $metadata['Account']['rules'][] = $rules; $metadata['Account']['members'][] = 'longTextField'; $rules = array('longTextField', 'type', 'type' => 'longtext'); $metadata['Account']['rules'][] = $rules; $metadata['Account']['members'][] = 'dateField'; $rules = array('dateField', 'type', 'type' => 'date'); $metadata['Account']['rules'][] = $rules; $metadata['Account']['members'][] = 'booleanField'; $rules = array('booleanField', 'boolean'); $metadata['Account']['rules'][] = $rules; $metadata['Account']['members'][] = 'integerField'; $rules = array('integerField', 'type', 'type' => 'integer'); $metadata['Account']['rules'][] = $rules; $metadata['Account']['members'][] = 'dateTimeField'; $rules = array('dateTimeField', 'type', 'type' => 'datetime'); $metadata['Account']['rules'][] = $rules; $metadata['Account']['members'][] = 'urlField'; $rules = array('urlField', 'url'); $metadata['Account']['rules'][] = $rules; $metadata['Account']['members'][] = 'floatField'; $rules = array('floatField', 'type', 'type' => 'float'); $metadata['Account']['rules'][] = $rules; $metadata['Account']['members'][] = 'longTextField'; $rules = array('longTextField', 'type', 'type' => 'longtext'); $metadata['Account']['rules'][] = $rules; $metadata['Account']['members'][] = 'blobField'; $rules = array('blobField', 'type', 'type' => 'blob'); $metadata['Account']['rules'][] = $rules; $metadata['Account']['members'][] = 'longBlobField'; $rules = array('longBlobField', 'type', 'type' => 'longblob'); $metadata['Account']['rules'][] = $rules; Account::setMetadata($metadata); $super = User::getByUsername('super'); Yii::app()->user->userModel = $super; $messageLogger = new MessageLogger(); $beforeRowCount = DatabaseCompatibilityUtil::getTableRowsCountTotal(); InstallUtil::autoBuildDatabase($messageLogger); $afterRowCount = DatabaseCompatibilityUtil::getTableRowsCountTotal(); $this->assertEquals($beforeRowCount, $afterRowCount); //Check Account fields $tableName = RedBeanModel::getTableName('Account'); $columns = R::$writer->getColumns($tableName); $this->assertEquals('text', $columns['newfield']); $this->assertEquals('varchar(128)', $columns['string128']); $this->assertEquals('text', $columns['string555']); $this->assertEquals('longtext', $columns['string100000']); $this->assertEquals('text', $columns['textfield']); $this->assertEquals('date', $columns['datefield']); $this->assertEquals('tinyint(1)', $columns['booleanfield']); $this->assertEquals('int(11) unsigned', $columns['integerfield']); $this->assertEquals('datetime', $columns['datetimefield']); $this->assertEquals('varchar(255)', $columns['urlfield']); $this->assertEquals('double', $columns['floatfield']); $this->assertEquals('longtext', $columns['longtextfield']); $this->assertEquals('blob', $columns['blobfield']); $this->assertEquals('longblob', $columns['longblobfield']); $account = new Account(); $account->name = 'Test Name'; $account->owner = $super; $randomString = str_repeat("Aa", 64); $account->string128 = $randomString; $this->assertTrue($account->save()); $metadata = Account::getMetadata(); foreach ($metadata['Account']['rules'] as $key => $rule) { if ($rule[0] == 'string128' && $rule[1] == 'length') { $metadata['Account']['rules'][$key]['max'] = 64; } } Account::setMetadata($metadata); InstallUtil::autoBuildDatabase($messageLogger); RedBeanModel::forgetAll(); $modifiedAccount = Account::getById($account->id); $this->assertEquals($randomString, $modifiedAccount->string128); //Check Account fields $tableName = RedBeanModel::getTableName('Account'); $columns = R::$writer->getColumns($tableName); $this->assertEquals('varchar(128)', $columns['string128']); }
protected static function buildWhereForRelatedAttributeThatIsItselfAHasManyRelation(RedBeanModelAttributeToDataProviderAdapter $modelAttributeToDataProviderAdapter, $joinTablesAdapter, $relationAttributeTableAliasName, $operatorType, $value, &$where, $whereKey) { assert('$joinTablesAdapter instanceof RedBeanModelJoinTablesQueryAdapter'); assert('is_string($relationAttributeTableAliasName)'); assert('is_string($operatorType)'); assert('is_array($value) && count($value) > 0'); assert('is_array($where)'); assert('is_int($whereKey)'); $relationAttributeName = $modelAttributeToDataProviderAdapter->getRelatedAttribute(); $relationAttributeModelClassName = $modelAttributeToDataProviderAdapter->getRelatedAttributeRelationModelClassName(); if ($relationAttributeModelClassName != 'CustomFieldValue') { //Until we can add a third parameter to the search adapter metadata, we have to assume we are only doing //this for CustomFieldValue searches. Below we have $joinColumnName, since we don't have any other way //of ascertaining this information for now. throw new NotSupportedException(); } if ($operatorType != 'oneOf') { //only support oneOf for the moment. Once we add allOf, need to have an alternative sub-query //below that uses if/else logic to compare count against how many possibles. then return 1 or 0. } $relationAttributeTableName = RedBeanModel::getTableName($relationAttributeModelClassName); $tableAliasName = $relationAttributeTableName; $joinColumnName = 'value'; $relationColumnName = RedBeanModel::getTableName($modelAttributeToDataProviderAdapter->getRelatedAttributeModelClassName()) . "_id"; $quote = DatabaseCompatibilityUtil::getQuote(); $where[$whereKey] = "(1 = (select 1 from {$quote}{$relationAttributeTableName}{$quote} {$tableAliasName} " . "where {$quote}{$tableAliasName}{$quote}.{$quote}{$relationColumnName}{$quote} = " . "{$quote}{$relationAttributeTableAliasName}{$quote}.id " . "and {$quote}{$tableAliasName}{$quote}.{$quote}{$joinColumnName}{$quote} " . DatabaseCompatibilityUtil::getOperatorAndValueWherePart($operatorType, $value) . " limit 1))"; }
/** * @depends testSetAttributesWithPostForCustomField */ public function testUpdateValueOnCustomFieldRows() { $values = array('A', 'B', 'C'); $customFieldData = CustomFieldData::getByName('updateItems'); $customFieldData->serializedData = serialize($values); $this->assertTrue($customFieldData->save()); $id = $customFieldData->id; $customField = new CustomField(); $customField->value = 'A'; $customField->data = $customFieldData; $this->assertTrue($customField->save()); $customField = new CustomField(); $customField->value = 'B'; $customField->data = $customFieldData; $this->assertTrue($customField->save()); $customField = new CustomField(); $customField->value = 'C'; $customField->data = $customFieldData; $this->assertTrue($customField->save()); $customField = new CustomField(); $customField->value = 'C'; $customField->data = $customFieldData; $this->assertTrue($customField->save()); $quote = DatabaseCompatibilityUtil::getQuote(); $customFieldTableName = RedBeanModel::getTableName('CustomField'); $baseCustomFieldTableName = RedBeanModel::getTableName('BaseCustomField'); $valueAttributeColumnName = 'value'; $dataAttributeColumnName = RedBeanModel::getForeignKeyName('CustomField', 'data'); $sql = "select {$quote}{$customFieldTableName}{$quote}.id from {$quote}{$customFieldTableName}{$quote} "; $sql .= "left join {$quote}{$baseCustomFieldTableName}{$quote} on "; $sql .= "{$quote}{$baseCustomFieldTableName}{$quote}.id = "; $sql .= "{$quote}{$customFieldTableName}{$quote}.basecustomfield_id "; $sql .= "where {$quote}{$dataAttributeColumnName}{$quote} = {$id}"; $ids = R::getCol($sql); $beans = R::batch($customFieldTableName, $ids); $customFields = RedBeanModel::makeModels($beans, 'CustomField'); $this->assertEquals(4, count($customFields)); $sql = "select {$quote}{$customFieldTableName}{$quote}.id from {$quote}{$customFieldTableName}{$quote} "; $sql .= "left join {$quote}{$baseCustomFieldTableName}{$quote} on "; $sql .= "{$quote}{$baseCustomFieldTableName}{$quote}.id = "; $sql .= "{$quote}{$customFieldTableName}{$quote}.basecustomfield_id "; $sql .= "where {$quote}{$dataAttributeColumnName}{$quote} = {$id} "; $sql .= "and {$quote}{$valueAttributeColumnName}{$quote} = 'B'"; $this->assertEquals(1, count(R::getCol($sql))); $sql = "select {$quote}{$customFieldTableName}{$quote}.id from {$quote}{$customFieldTableName}{$quote} "; $sql .= "left join {$quote}{$baseCustomFieldTableName}{$quote} on "; $sql .= "{$quote}{$baseCustomFieldTableName}{$quote}.id = "; $sql .= "{$quote}{$customFieldTableName}{$quote}.basecustomfield_id "; $sql .= "where {$quote}{$dataAttributeColumnName}{$quote} = {$id} "; $sql .= "and {$quote}{$valueAttributeColumnName}{$quote} = 'C'"; $this->assertEquals(2, count(R::getCol($sql))); $sql = "select {$quote}{$customFieldTableName}{$quote}.id from {$quote}{$customFieldTableName}{$quote} "; $sql .= "left join {$quote}{$baseCustomFieldTableName}{$quote} on "; $sql .= "{$quote}{$baseCustomFieldTableName}{$quote}.id = "; $sql .= "{$quote}{$customFieldTableName}{$quote}.basecustomfield_id "; $sql .= "where {$quote}{$dataAttributeColumnName}{$quote} = {$id} "; $sql .= "and {$quote}{$valueAttributeColumnName}{$quote} = 'E'"; $this->assertEquals(0, count(R::getCol($sql))); CustomField::updateValueByDataIdAndOldValueAndNewValue($id, 'C', 'E'); $sql = "select {$quote}{$customFieldTableName}{$quote}.id from {$quote}{$customFieldTableName}{$quote} "; $sql .= "left join {$quote}{$baseCustomFieldTableName}{$quote} on "; $sql .= "{$quote}{$baseCustomFieldTableName}{$quote}.id = "; $sql .= "{$quote}{$customFieldTableName}{$quote}.basecustomfield_id "; $sql .= "where {$quote}{$dataAttributeColumnName}{$quote} = {$id} "; $sql .= "and {$quote}{$valueAttributeColumnName}{$quote} = 'B'"; $this->assertEquals(1, count(R::getCol($sql))); $sql = "select {$quote}{$customFieldTableName}{$quote}.id from {$quote}{$customFieldTableName}{$quote} "; $sql .= "left join {$quote}{$baseCustomFieldTableName}{$quote} on "; $sql .= "{$quote}{$baseCustomFieldTableName}{$quote}.id = "; $sql .= "{$quote}{$customFieldTableName}{$quote}.basecustomfield_id "; $sql .= "where {$quote}{$dataAttributeColumnName}{$quote} = {$id} "; $sql .= "and {$quote}{$valueAttributeColumnName}{$quote} = 'C'"; $this->assertEquals(0, count(R::getCol($sql))); $sql = "select {$quote}{$customFieldTableName}{$quote}.id from {$quote}{$customFieldTableName}{$quote} "; $sql .= "left join {$quote}{$baseCustomFieldTableName}{$quote} on "; $sql .= "{$quote}{$baseCustomFieldTableName}{$quote}.id = "; $sql .= "{$quote}{$customFieldTableName}{$quote}.basecustomfield_id "; $sql .= "where {$quote}{$dataAttributeColumnName}{$quote} = {$id} "; $sql .= "and {$quote}{$valueAttributeColumnName}{$quote} = 'E'"; $this->assertEquals(2, count(R::getCol($sql))); }
public function save($runValidation = true) { if (!parent::save($runValidation)) { return false; } foreach ($this->deferredRelateBeans as $bean) { if ($this->linkType == RedBeanModel::LINK_TYPE_POLYMORPHIC) { if ($this->bean->id == null) { R::store($this->bean); } $polyIdFieldName = strtolower($this->linkName) . '_id'; $polyTypeFieldName = strtolower($this->linkName) . '_type'; $bean->{$polyTypeFieldName} = $this->bean->getMeta('type'); $bean->{$polyIdFieldName} = $this->bean->id; if (!RedBeanDatabase::isFrozen()) { $tableName = RedBeanModel::getTableName($this->modelClassName); RedBeanColumnTypeOptimizer::optimize($tableName, $polyIdFieldName, 'id'); } } else { ZurmoRedBeanLinkManager::link($bean, $this->bean, $this->resolveLinkNameForCasing()); if (!RedBeanDatabase::isFrozen()) { $tableName = RedBeanModel::getTableName($this->modelClassName); $columnName = RedBeanModel::getTableName($this->relatedModelClassName) . '_id'; $columnName = ZurmoRedBeanLinkManager::resolveColumnPrefix($this->resolveLinkNameForCasing()) . $columnName; RedBeanColumnTypeOptimizer::optimize($tableName, $columnName, 'id'); } } R::store($bean); } $this->deferredRelateBeans = array(); $tableName = RedBeanModel::getTableName($this->relatedModelClassName); foreach ($this->deferredUnrelateBeans as $bean) { if (!$this->owns) { ZurmoRedBeanLinkManager::breakLink($bean, $tableName, $this->resolveLinkNameForCasing()); R::store($bean); } else { R::trash($bean); } } $this->deferredUnrelateBeans = array(); return true; }
public function getTableName(RedBean_OODBBean $bean = null) { if ($bean == null) { $bean = R::dispense(RedBeanModel::getTableName($this->modelClassName)); } $types = array($this->bean->getMeta("type"), $bean->getMeta("type")); sort($types); $tableName = implode("_", $types); if ($this->linkName != null) { $tableName = strtolower($this->linkName) . '_' . $tableName; } return $tableName; }
/** * Get all added model names and ids from read permission subscription table * @param $serviceName * @param $modelClassName * @param $lastUpdateTimestamp * @param $user * @return array */ public static function getAddedModelNamesAndIdsFromReadSubscriptionTable($serviceName, $modelClassName, $lastUpdateTimestamp, $user) { assert('$user instanceof User'); $tableName = self::getSubscriptionTableName($modelClassName); $modelTableName = RedBeanModel::getTableName($modelClassName); $dateTime = DateTimeUtil::convertTimestampToDbFormatDateTime($lastUpdateTimestamp); $sql = "SELECT {$tableName}.modelid, {$modelTableName}.name FROM {$tableName}" . " left join " . ModelCreationApiSyncUtil::TABLE_NAME . " isct " . " on isct.modelid = {$tableName}.modelid" . " AND isct.servicename = '" . $serviceName . "'" . " AND isct.modelclassname = '" . $modelClassName . "'" . " left join {$modelTableName} on {$modelTableName}.id = {$tableName}.modelid" . " WHERE {$tableName}.userid = " . $user->id . " AND {$tableName}.subscriptiontype = " . self::TYPE_ADD . " AND {$tableName}.modifieddatetime >= '" . $dateTime . "'" . " AND isct.modelid is null" . " order by {$tableName}.modifieddatetime ASC, {$tableName}.modelid ASC"; $modelIdsRows = R::getAll($sql); $modelIds = array(); if (is_array($modelIdsRows) && !empty($modelIdsRows)) { foreach ($modelIdsRows as $modelIdRow) { $modelIds[$modelIdRow['modelid']] = $modelIdRow['name']; } } return $modelIds; }