Saltar para o conteúdo principal
Versão: Próximo

EntitySelection

An entity selection is an object containing one or more reference(s) to entities belonging to the same Dataclass. Uma seleção de entidades pode conter 0, 1 ou X entidades da dataclass -- onde X pode representar o número total de entidades contidas na dataclass.

Entity selections can be created from existing selections using various functions of the DataClass class such as .all() or .query(), or functions of the EntityClass class itself, such as .and() or orderBy(). You can also create blank entity selections using the dataClass.newSelection() function or the Create new selection command.

Resumo

[index] : 4D.Entity    allows you to access entities within the entity selection using the standard collection syntax
.attributeName : Collection
.attributeName : 4D.EntitySelection
    a "projection" of values for the attribute in the entity selection
.add( entity : 4D.Entity ) : 4D.EntitySelection
.add( entitySelection : 4D.EntitySelection ) : 4D.EntitySelection
    adds the specified entity or entitySelection to the original entity selection and returns the modified entity selection
.and( entity : 4D.Entity ) : 4D.EntitySelection
.and( entitySelection : 4D.EntitySelection ) : 4D.EntitySelection
    combines the entity selection with an entity or entitySelection parameter using the logical AND operator
.at( index : Integer ) : 4D.Entity     returns the entity at position index, allowing for positive and negative integer
.average( attributePath : Text ) : Real    returns the arithmetic mean (average) of all the non-null values of attributePath in the entity selection
.contains( entity : 4D.Entity ) : Boolean    returns true if entity reference belongs to the entity selection
.copy( { option : Integer } ) : 4D.EntitySelection    returns a copy of the original entity selection
.count( attributePath : Text ) : Real    returns the number of entities in the entity selection with a non-null value in attributePath
.distinct( attributePath : Text { ; options : Integer } ) : Collection    returns a collection containing only distinct (different) values from the attributePath in the entity selection
.distinctPaths( attribute : Text ) : Collection    returns a collection of distinct paths found in the indexed object attribute for the entity selection
.drop( { mode : Integer } ) : 4D.EntitySelection    removes the entities belonging to the entity selection from the table related to its dataclass within the datastore

| .extract( attributePath : Text { ; option : Integer } ) : Collection
.extract( attributePath { ; targetPath } { ; ...attributePathN : Text ; targetPathN : Text } ) : Collection
    returns a collection containing attributePath values extracted from the entity selection | | .first() : 4D.Entity    returns a reference to the entity in the first position of the entity selection | | .getDataClass() : 4D.DataClass    returns the dataclass of the entity selection | | .getRemoteContextAttributes() : Text    returns information about the optimization context used by the entity | | .isAlterable() : Boolean    returns True if the entity selection is alterable | | .isOrdered() : Boolean    returns True if the entity selection is ordered | | .last() : 4D.Entity    returns a reference to the entity in last position of the entity selection | | .length : Integer    returns the number of entities in the entity selection | | .max( attributePath : Text ) : any    returns the highest (or maximum) value among all the values of attributePath in the entity selection | | .min( attributePath : Text ) : any     returns the lowest (or minimum) value among all the values of attributePath in the entity selection | | .minus( entity : 4D.Entity { ; keepOrder : Integer } ) : 4D.EntitySelection
.minus( entitySelection : 4D.EntitySelection { ; keepOrder : Integer } ) : 4D.EntitySelection
    excludes from the entity selection to which it is applied the entity or the entities of entitySelection and returns the resulting entity selection | | .or( entity : 4D.Entity ) : 4D.EntitySelection
.or( entitySelection : 4D.EntitySelection ) : 4D.EntitySelection
    combines the entity selection with the entity or entitySelection parameter using the logical (not exclusive) OR operator | | .orderBy( pathString : Text ) : 4D.EntitySelection
.orderBy( pathObjects : Collection ) : 4D.EntitySelection
    returns a new ordered entity selection containing all entities of the entity selection in the order specified by pathString or pathObjects criteria | | .orderByFormula( formulaString : Text { ; sortOrder : Integer } { ; settings : Object} ) : 4D.EntitySelection
.orderByFormula( formulaObj : Object { ; sortOrder : Integer } { ; settings : Object} ) : 4D.EntitySelection
    returns a new, ordered entity selection | | .query( queryString : Text { ; ...value : any } { ; querySettings : Object } ) : 4D.EntitySelection
.query( formula : Object { ; querySettings : Object } ) : 4D.EntitySelection
    searches for entities that meet the search criteria specified in queryString or formula and (optionally) value(s) among all the entities in the entity selection | | .queryPath : Text    contains a detailed description of the query as it was actually performed by 4D | | .queryPlan : Text     contains a detailed description of the query just before it is executed (i.e., the planned query) | | .refresh()    immediately "invalidates" the entity selection data in the local ORDA cache | | .selected( selectedEntities : 4D.EntitySelection ) : Object    returns an object describing the position(s) of selectedEntities in the original entity selection | | .slice( startFrom : Integer { ; end : Integer } ) : 4D.EntitySelection    returns a portion of an entity selection into a new entity selection | | .sum( attributePath : Text ) : Real    returns the sum for all attributePath values in the entity selection | | .toCollection( { options : Integer { ; begin : Integer { ; howMany : Integer } } ) : Collection
.toCollection( filterString : Text {; options : Integer { ; begin : Integer { ; howMany : Integer }}} ) : Collection
.toCollection( filterCol : Collection {; options : Integer { ; begin : Integer { ; howMany : Integer }}} ) : Collection
    creates and returns a collection where each element is an object containing a set of properties and values |

Criar uma seleção de entidades (entity selection)

Create entity selection ( dsTable : Table { ; settings : Object } ) : 4D.EntitySelection

ParâmetroTipoDescrição
dsTableTabela->Tabela do banco de dados 4D cuja seleção atual se utilizará para construir a seleção de entidades
settingsObject->Opção de construção: context
Resultados4D. EntitySelection<-Seleção de entidades que coincidem com a classe de dados relacionada com a tabela dada

Descrição

The Create entity selection command builds and returns a new, alterable entity selection related to the dataclass matching the given dsTable, according to the current selection of this table.

If the current selection is sorted, an ordered entity selection is created (the order of the current selection is kept). Se a seleção atual não for ordenada, se cria uma seleção de entidades não ordenada.

If the dsTable is not exposed in ds, an error is returned. Esse comando não pode usado com uma datastore remota.

In the optional settings parameter, you can pass an object containing the following property:

PropriedadeTipoDescrição
contextTextLabel for the optimization context applied to the entity selection.

Exemplo

var $employees : cs. EmployeeSelection ALL RECORDS([Employee])
$employees:=Create entity selection([Employee])
// A entity selection $employees agora contém um conjunto de referências
// em todas as entidades relacionadas com a classe de dados Employee

Veja também

dataClass.newSelection()

USE ENTITY SELECTION

USE ENTITY SELECTION (entitySelection)

ParâmetroTipoDescrição
entitySelectionEntitySelection->Seleção de entidades

Descrição

The USE ENTITY SELECTION command updates the current selection of the table matching the dataclass of the entitySelection parameter, according to the content of the entity selection.

This command cannot be used with a Remote datastore.

info

Esse comando foi projetado para fazer com que as seleções de corrente 4D se beneficiem do poder das consultas ORDA. For performance reasons, in 4D single-user and 4D Server, the command directly connects entitySelection to the current selection. Therefore, once entitySelection has been used, it must not be reused or altered afterwards.

nota

After a call to USE ENTITY SELECTION, the first record of the updated current selection (if not empty) becomes the current record, but it is not loaded in memory. If you need to use the values of the fields in the current record, use the LOAD RECORD command after the USE ENTITY SELECTION command.

Exemplo

var $entitySel : cs.EmployeeSelection

$entitySel:=ds.Employee.query("lastName = :1"; "M@") //$entitySel está relacionado à classe de dados Employee
REDUCE SELECTION([Employee];0)
USE ENTITY SELECTION($entitySel) //A seleção atual da tabela Employee é atualizada

[index]

História
ReleaseMudanças
17Adicionado

[index] : 4D.Entity

Descrição

The EntitySelection[index] notation allows you to access entities within the entity selection using the standard collection syntax: pass the position of the entity you want to get in the index parameter.

Lembre que a entidade correspondente é recarregada a partir da datastore.

index can be any number between 0 and .length-1.

  • If index is out of range, an error is returned.
  • If index corresponds to a dropped entity, a Null value is returned.
caution

EntitySelection[index] is a non assignable expression, which means that it cannot be used as en editable entity reference with methods like .lock() or .save(). Para trabalhar com a entidade correspondente, é necessário atribuir a expressão devolvida a uma expressão atribuível, como uma variável. Exemplos:

 $sel:=ds. Employee.all() //criação da entity selection
//declarações não válidas:
$result:=$sel[0].lock() //NÃO funcionará
$sel[0].lastName:="Smith" //NÃO funcionará
$result:=$sel[0].save() //NÃO funcionará
//valid code:
$entity:=$sel[0] //OK
$entity.lastName:="Smith" //OK
$entity.save() //OK

Exemplo

 var $employees : cs. EmployeeSelection
var $employee : cs. EmployeeEntity
$employees:=ds. Employee.query("lastName = :1";"H@")
$employee:=$employees[2] // A terceira entidade da seleção de entidades $employees se recarrega do banco de dados

.attributeName

História
ReleaseMudanças
17Adicionado

.attributeName : Collection
.attributeName : 4D.EntitySelection

Descrição

Any dataclass attribute can be used as a property of an entity selection to return a "projection" of values for the attribute in the entity selection. Projected values can be a collection or a new entity selection, depending on the kind (storage or relation) of the attribute.

  • If attributeName kind is storage: .attributeName returns a collection of values of the same type as attributeName.
  • If attributeName kind is relatedEntity: .attributeName returns a new entity selection of related values of the same type as attributeName. Se eliminam os duplicados (se devolve uma seleção de entidades desordenada).
  • If attributeName kind is relatedEntities: .attributeName returns a new entity selection of related values of the same type as attributeName. Se eliminam os duplicados (se devolve uma seleção de entidades desordenada).

Quando se utiliza um atributo de relação como propriedade de uma seleção de entidades, o resultado é sempre outra seleção de entidades, mesmo que só se devolva uma entidade. If the original entity selection and the entitySelection parameter are empty, an empty entity selection is returned.

Se o atributo não existir na seleção de entidades, se devolve um erro.

Exemplo 1

Projeção de valores de armazenamento:

 var $firstNames : Collection
$entitySelection:=ds. Employee.all()
$firstNames:=$entitySelection.firstName // firstName é um string

A coleção resultante é uma coleção de strings, por exemplo:

[
"Joanna",
"Alexandra",
"Rick"
]

Exemplo 2

Projeção da entidade relacionada:

 var $es; $entitySelection : cs. EmployeeSelection
$entitySelection:=ds. Employee.all()
$es:=$entitySelection.employer // employer é relacionada aum Company dataClass

O objeto resultane é uma seleção de entidade da Empresa com duplicações removidas (se houver).

Exemplo 3

Projeção de entidades relacionadas:

 var $es : cs. EmployeeSelection
$es:=ds. Employee.all().directReports // directReports é relacionada a dataclasse Funcionário

O objeto resultante é uma seleção de entidade da dataclasse Funcionario sem duplicatas (se houver).

.add()

História
ReleaseMudanças
18 R6Support of entitySelection parameter
18 R5Compatível apenas com seleções de entidade alteráveis
17Adicionado

.add( entity : 4D.Entity ) : 4D.EntitySelection
.add( entitySelection : 4D.EntitySelection ) : 4D.EntitySelection

ParâmetroTipoDescrição
entity4D. Entity->Entidade que deve ser adicinonada à entity selection
entitySelection4D. EntitySelection->Seleção entidade paara ser adicionado a sellleção entidade originaal
Resultados4D. EntitySelection->Entity selection including the added entity or entitySelection

Descrição

The .add() function adds the specified entity or entitySelection to the original entity selection and returns the modified entity selection.

Esta função não modifica a entity selection original.

aviso

The entity selection must be alterable, i.e. it has been created for example by .newSelection() or Create entity selection, otherwise .add() will return an error. As entity selections partilháveis não aceitam a adição de entidades. For more information, please refer to the Shareable or alterable entity selections section.

Adicionar uma entidade

  • If the entity selection is ordered, entity is added at the end of the selection. Se uma referência a mesma entidade já pertencer a seleção de entidades, se duplica e se adiciona uma nova referência.
  • If the entity selection is unordered, entity is added anywhere in the selection, with no specific order.

Adicionar uma seleção de entidades

  • If the entity selection is ordered, its order is kept and entitySelection is added at the end of the selection. If references to the same entities of entitySelection already belong to the entity selection, they are duplicated and new references are added.
  • Se a seleção de entidade nãofor ordenada, ela fica ordenada.

For more information, please refer to the Ordered or unordered entity selection section.

A entity selection modificada é devolvida pela função, de modo que as chamadas à função podem ser encadeados.

An error occurs if entity and the entity selection are not related to the same Dataclass. If entity is Null, no error is raised.

Exemplo 1

 var $employees : cs. EmployeeSelection
var $employee : cs. EmployeeEntity
$employees:=ds. Employee.query("lastName = :1";"S@")
$employee:=ds. Employee.new()
$employee.lastName:="Smith"
$employee.save()
$employees.add($employee) //A entidade $employee se adiciona a entity selection $employees

Exemplo 2

As chamadas à função podem ser encadeadas:

 var $sel : cs. ProductSelection
var $p1;$p2;$p3 : cs. ProductEntity

$p1:=ds. Product.get(10)
$p2:=ds. Product.get(11)
$p3:=ds. Product.get(12)
$sel:=ds. Product.query("ID &gt; 50")
$sel:=$sel.add($p1).add($p2).add($p3)

Exemplo 3

Em uma interface de usuário, temos duas listas. O usuário seleciona itens da lista 1 e as adiciona na lista 2.

$sellist2:=$sellist2.add($sellist1)

.and()

História
ReleaseMudanças
17Adicionado

.and( entity : 4D.Entity ) : 4D.EntitySelection
.and( entitySelection : 4D.EntitySelection ) : 4D.EntitySelection

ParâmetroTipoDescrição
entity4D. Entity->Entidade a intersectar
entitySelection4D. EntitySelection->Entity selection a intersectar
Resultados4D. EntitySelection<-Entity selection resultante da intersecção com o operador lógico AND

Descrição

The .and() function combines the entity selection with an entity or entitySelection parameter using the logical AND operator; it returns a new, unordered entity selection that contains only the entities that are referenced in both the entity selection and the parameter.

  • If you pass entity as parameter, you combine this entity with the entity selection. Se a entidade pertencer à entity selection, se devolve uma nova entity selection que só contém a entidade. Senão, uma seleção de entidades vazia é retornada.
  • If you pass entitySelection as parameter, you combine both entity selections. Uma nova seleção de entidade que contenha só as entidades que são referenciadas em ambas as seleções sejam retornadas. Senão, uma nova seleção de entidade contém a seleção de entidade original e a entidade é retornada.

You can compare ordered and/or unordered entity selections. A seleção resultante é sempre desordenada.

If the original entity selection or the entitySelection parameter is empty, or if the entity is Null, an empty entity selection is returned.

Se a entity selection inicial e o parâmetro não forem relacionados com a mesma dataclass, se produz um erro.

Exemplo 1

 var $employees; $result : cs.EmployeeSelection
var $employee : cs.EmployeeEntity
$employees:=ds.Employee.query("lastName = :1";"H@")
//The $employees entity selection contains the entity
//with primary key 710 and other entities
//for ex. "Colin Hetrick" / "Grady Harness" / "Sherlock Holmes" (primary key 710)
$employee:=ds.Employee.get(710) // Returns "Sherlock Holmes"

$result:=$employees.and($employee) //$result is an entity selection containing
//only the entity with primary key 710 ("Sherlock Holmes")

Exemplo 2

Se quisermos ter uma seleção de empregados chamados "Jones" que morem em Nova York:

 var $sel1; $sel2; $sel3 : cs.EmployeeSelection
$sel1:=ds.Employee.query("name =:1";"Jones")
$sel2:=ds.Employee.query("city=:1";"New York")
$sel3:=$sel1.and($sel2)

.at()

História
ReleaseMudanças
20Adicionado

.at( index : Integer ) : 4D.Entity

ParâmetroTipoDescrição
indexInteger->Índice da entidade a devolver
Resultados4D. Entity<-A entidade nesse índice

Descrição

The .at() function returns the entity at position index, allowing for positive and negative integer.

If index is negative (from -1 to -n with n : length of the entity selection), the returned entity will be based on the reverse order of the entity selection.

The function returns Null if index is beyond entity selection limits.

Exemplo

var $employees : cs.EmployeeSelection
var $emp1; $emp2 : cs.EmployeeEntity
$employees:=ds.Employee.query("lastName = :1";"H@")
$emp1:=$employees.at(2) //3rd entity of the $employees entity selection
$emp2:=$employees.at(-3) //starting from the end, 3rd entity
//of the $employees entity selection

.average()

História
ReleaseMudanças
18 R6Retorna indefinido se uma seleção de entidade for vazia
17Adicionado

.average( attributePath : Text ) : Real

ParâmetroTipoDescrição
attributePathText->Rota do atributo que se utilizará para o cálculo
ResultadosReal<-Media aritmética (média) dos valores das entidades para o atributo (Não se define para uma entity selection vazia)

Descrição

The .average() function returns the arithmetic mean (average) of all the non-null values of attributePath in the entity selection.

Pass in the attributePath parameter the attribute path to evaluate.

Só são levados em consideração os valores numéricos para o cálculo. Note however that, if the attributePath of the entity selection contains mixed value types, .average() takes all scalar elements into account to calculate the average value.

Os valores de tipo Date são convertidos em valores numéricos (segundos) e são usados para calcular a média.

.average() returns undefined if the entity selection is empty or attributePath does not contain numerical values.

Um erro é retornado se:

  • attributePath is a related attribute,
  • attributePath designates an attribute that does not exist in the entity selection dataclass.

Exemplo

Se quisermos obter uma lista de funcionários cujo salário for superior ao salário médio:

 var $averageSalary : Real
var $moreThanAv : cs.EmployeeSelection
$averageSalary:=ds.Employee.all().average("salary")
$moreThanAv:=ds.Employee.query("salary > :1";$averageSalary)

.contains()

História
ReleaseMudanças
17Adicionado

.contains( entity : 4D.Entity ) : Boolean

ParâmetroTipoDescrição
entity4D. Entity->Entidade a ser avaliada
ResultadosParâmetros<-Truse se a entidade pertencer à entity selection, senão False

Descrição

The .contains() function returns true if entity reference belongs to the entity selection, and false otherwise.

In entity, specify the entity to search for in the entity selection. Se a entidade for Null, a função devolverá false.

If entity and the entity selection do not belong to the same dataclass, an error is raised.

Exemplo

 var $employees : cs.EmployeeSelection
var $employee : cs.EmployeeEntity

$employees:=ds.Employee.query("lastName=:1";"H@")
$employee:=ds.Employee.get(610)

If($employees.contains($employee))
ALERT("The entity with primary key 610 has a last name beginning with H")
Else
ALERT("The entity with primary key 610 does not have a last name beginning with H")
End if

.count()

História
ReleaseMudanças
17Adicionado

.count( attributePath : Text ) : Real

ParâmetroTipoDescrição
attributePathText->Rota do atributo que se utilizará para o cálculo
ResultadosReal<-Number of non null attributePath values in the entity selection

Descrição

The .count() function returns the number of entities in the entity selection with a non-null value in attributePath.

Só são levados em consideração os valores escalares. Os valores de tipo objeto ou coleção são considerados valores nulos.

Um erro é retornado se:

  • attributePath is a related attribute,
  • attributePath is not found in the entity selection dataclass.

Exemplo

Se quisermos encontrar o número total de empregados para uma empresa sem contar aqueles cujos titulos de mprego não foram especificados:

 var $sel : cs.EmployeeSelection
var $count : Real

$sel:=ds.Employee.query("employer = :1";"Acme, Inc")
$count:=$sel.count("jobtitle")

.copy()

História
ReleaseMudanças
18 R5Adicionado

.copy( { option : Integer } ) : 4D.EntitySelection

ParâmetroTipoDescrição
optionInteger->ck shared: return a shareable entity selection
Resultados4D. EntitySelection<-Cópia da entity selection

Descrição

The .copy() function returns a copy of the original entity selection.

Esta função não modifica a seleção de entidades original.

By default, if the option parameter is omitted, the function returns a new, alterable entity selection (even if the function is applied to a shareable entity selection). Pass the ck shared constant in the option parameter if you want to create a shareable entity selection.

For information on the shareable property of entity selections, please refer to the Shareable or alterable entity selections section.

Exemplo

Se criar uma nova seleção de entidade vazia de produtos quando o formulário for carregado:

 Case of
:(Form event code=On Load)
Form.products:=ds.Products.newSelection()
End case

Então esta seleção de entidades é atualizada com produtos e se quiser compartilhar os produtos entre vários processos. Se copiar a seleçãod a entidade Form.products como compartilhável:

 ...
// The Form.products entity selection is updated
Form.products.add(Form.selectedProduct)

Use(Storage)
If(Storage.products=Null)
Storage.products:=New shared object()
End if

Use(Storage.products)
Storage.products:=Form.products.copy(ck shared)
End use
End use

.distinct()

História
ReleaseMudanças
20Support of dk count values
17Adicionado

.distinct( attributePath : Text { ; options : Integer } ) : Collection

ParâmetroTipoDescrição
attributePathText->Rota do atributo cujos valores quer obter
optionsInteger->dk diacritical, dk count values
ResultadosCollection<-Coleção apenas com valores distintos

Descrição

The .distinct() function returns a collection containing only distinct (different) values from the attributePath in the entity selection.

A coleção retornada é ordenada automaticamente. Null values are not returned.

In the attributePath parameter, pass the entity attribute whose distinct values you want to get. Só valores escalares (texto, número, booleano, ou data) podemser manejados. If the attributePath leads to an object property that contains values of different types, they are first grouped by type and sorted afterwards. Se attributePath levar a uma propriedade de objeto que conter valores de diferentes tipos, primeiro se agrupam por tipo e se ordenam depois.

  1. booleans
  2. strings
  3. números
  4. datas

You can use the [] notation to designate a collection when attributePath is a path within an object (see examples).

In the options parameter, you can pass one or a combination of the following constants:

ParâmetrosValorComentário
dk diacritical8A avaliação é sensível a maiúsculas e minúsculas e diferencia os caracteres acentuados. Como padrão, uma avaliação não-diacrítica é realizada.
dk count values32Devolve a contagem de entidades para cada valor distinto. When this option is passed, .distinct() returns a collection of objects containing a pair of {"value":*value*; "count":*count*} properties.
nota

The dk count values option is only available with storage attributes of type boolean, string, number, and date.

Um erro é retornado se:

  • attributePath is a related attribute,
  • attributePath is not found in the entity selection dataclass.

Exemplos

Se quiser obter uma coleção que contenha um só elemento por nome de país:

var $countries : Collection
$countries:=ds. Employee.all().distinct("address.country")

nicknames is a collection and extra is an object attribute:

$values:=ds. Employee.all().distinct("extra.nicknames[].first")

Pretende obter o número de nomes de funções diferentes na empresa:

var $jobs : Collection
$jobs:=ds. Employee.all().distinct("jobName";dk count values)
//$jobs[0]={"value":"Developer";"count":17}
//$jobs[1]={"value":"Office manager";"count":5}
//$jobs[2]={"value":"Accountant";"count":2}
//...

.distinctPaths()

História
ReleaseMudanças
20Adicionado

.distinctPaths( attribute : Text ) : Collection

ParâmetroTipoDescrição
atributoText->Nome do atributo do objecto cujos caminhos pretende obter
ResultadosCollection<-Nova colecção com caminhos distintos

Descrição

The .distinctPaths() function returns a collection of distinct paths found in the indexed object attribute for the entity selection.

If attribute is not an indexed object attribute, an error is generated.

After the call, the size of the returned collection is equal to the number of distinct paths found in attribute for the entity selection. Os caminhos são devolvidos como cadeias de caracteres, incluindo atributos e colecções aninhados, por exemplo "info.address.number" ou "children[].birthdate". Entities with a null value in the attribute are not taken into account.

Exemplo

You want to get all paths stored in a fullData object attribute:

var $paths : Collection
$paths:=ds. Employee.all().distinctPaths("fullData")
//$paths[0]="age"
//$paths[1]="Children"
//$paths[2]="Children[].age"
//$paths[3]="Children[].name"
//$paths[4]="Children.length"
///...
nota

length is automatically added as path for nested collection properties.

.drop()

História
ReleaseMudanças
17Adicionado

.drop( { mode : Integer } ) : 4D.EntitySelection

ParâmetroTipoDescrição
modeInteger->dk stop dropping on first error: stops method execution on first non-droppable entity
Resultados4D. EntitySelection<-Empty entity selection if successful, else entity selection containing non-droppable entity(ies)

Descrição

The .drop() function removes the entities belonging to the entity selection from the table related to its dataclass within the datastore. A entity selection permanece na memória.

A eliminação de entidades é permanente e não pode ser desfeita. É recomendado chamar esta ação em uma transação para ter uma opção de recuperação.

If a locked entity is encountered during the execution of .drop(), it is not removed. Como padrão o método processa todas as entidades da seleção de entidades e retorna as entidades não elimináveis na entity selection. If you want the method to stop execution at the first encountered non-droppable entity, pass the dk stop dropping on first error constant in the mode parameter.

Exemplo

Example without the dk stop dropping on first error option:

 var $employees; $notDropped : cs.EmployeeSelection
$employees:=ds.Employee.query("firstName=:1";"S@")
$notDropped:=$employees.drop() // $notDropped is an entity selection containing all the not dropped entities
If($notDropped.length=0) //The delete action is successful, all the entities have been deleted
ALERT("You have dropped "+String($employees.length)+" employees") //The dropped entity selection remains in memory
Else
ALERT("Problem during drop, try later")
End if

Example with the dk stop dropping on first error option:

 var $employees; $notDropped : cs.EmployeeSelection
$employees:=ds.Employee.query("firstName=:1";"S@")
$notDropped:=$employees.drop(dk stop dropping on first error) //$notDropped is an entity selection containing the first not dropped entity
If($notDropped.length=0) //The delete action is successful, all the entities have been deleted
ALERT("You have dropped "+String($employees.length)+" employees") //The dropped entity selection remains in memory
Else
ALERT("Problem during drop, try later")
End if

.extract()

História
ReleaseMudanças
18 R3Adicionado

.extract( attributePath : Text { ; option : Integer } ) : Collection
.extract( attributePath { ; targetPath } { ; ...attributePathN : Text ; targetPathN : Text } ) : Collection

ParâmetroTipoDescrição
attributePathText->Rota de atributo cujos valores serão extraídos para nova coleção
targetpathText->Rota ou nome do atributo objetivo
optionInteger->ck keep null: include null attributes in the returned collection (ignored by default)
ResultadosCollection<-Coleção contendo valores extraídos

Descrição

The .extract() function returns a collection containing attributePath values extracted from the entity selection.

attributePath can refer to:

  • um atributo escalar de dataclass,
  • entidade relacionada,
  • entidades relacionadas.

If attributePath is invalid, an empty collection is returned.

Esta função aceita duas sintaxes.

.extract( attributePath : Text { ; option : Integer } ) : Collection

With this syntax, .extract() populates the returned collection with the attributePath values of the entity selection.

By default, entities for which attributePath is null or undefined are ignored in the resulting collection. You can pass the ck keep null constant in the option parameter to include these values as null elements in the returned collection.

  • Dataclass attributes with .kind = "relatedEntity" are extracted as a collection of entities (duplications are kept).
  • Dataclass attributes with .kind = "relatedEntities" are extracted as a collection of entity selections.

.extract ( attributePath ; targetPath { ; ...attributePathN ; ... targetPathN}) : Collection

With this syntax, .extract() populates the returned collection with the attributePath properties. Each element of the returned collection is an object with targetPath properties filled with the corresponding attributePath properties. Null values are kept (option parameter is ignored with this syntax).

If several attributePath are given, a targetPath must be given for each. Only valid pairs [attributePath, targetPath] are extracted.

  • Dataclass attributes with .kind = "relatedEntity" are extracted as an entity.
  • Dataclass attributes with .kind = "relatedEntities" are extracted as an entity selection.

As entidades de uma colecção de entidades acedidas por [ ] não são recarregadas da base de dados.

Exemplo

Dada a seguinte tabela e relação:

 var $firstnames; $addresses; $mailing; $teachers : Collection
//
//
//$firstnames is a collection of Strings


$firstnames:=ds.Teachers.all().extract("firstname")
//
//$addresses is a collection of entities related to dataclass Address
//Null values for address are extracted
$addresses:=ds.Teachers.all().extract("address";ck keep null)
//
//
//$mailing is a collection of objects with properties "who" and "to"
//"who" property content is String type
//"to" property content is entity type (Address dataclass)
$mailing:=ds.Teachers.all().extract("lastname";"who";"address";"to")
//
//
//$mailing is a collection of objects with properties "who" and "city"
//"who" property content is String type
//"city" property content is String type
$mailing:=ds.Teachers.all().extract("lastname";"who";"address.city";"city")
//
//$teachers is a collection of objects with properties "where" and "who"
//"where" property content is String
//"who" property content is an entity selection (Teachers dataclass)
$teachers:=ds.Address.all().extract("city";"where";"teachers";"who")
//
//$teachers is a collection of entity selections
$teachers:=ds.Address.all().extract("teachers")

.first()

História
ReleaseMudanças
17Adicionado

.first() : 4D.Entity

ParâmetroTipoDescrição
Resultados4D. Entity<-Referência para a primeira entidade da seleção da entidade (Null se a seleção estiver vazia)

Descrição

The .first() function returns a reference to the entity in the first position of the entity selection.

O resultado desta função é similar a:

 $entity:=$entitySel[0]

Há, entretanto, uma diferença entre ambas as afirmações quando a seleção estiver vazia:

 var $entitySel : cs.EmpSelection
var $entity : cs.EmpEntity
$entitySel:=ds.Emp.query("lastName = :1";"Nonexistentname") //no matching entity
//entity selection is then empty
$entity:=$entitySel.first() //returns Null
$entity:=$entitySel[0] //generates an error

Exemplo

 var $entitySelection : cs.EmpSelection
var $entity : cs.EmpEntity
$entitySelection:=ds.Emp.query("salary > :1";100000)
If($entitySelection.length#0)
$entity:=$entitySelection.first()
End if

.getDataClass()

História
ReleaseMudanças
17 R5Adicionado

.getDataClass() : 4D.DataClass

ParâmetroTipoDescrição
Resultados4D. DataClass<-Objeto dataclass ao qual a seleção de entidade pertence

Descrição

The .getDataClass() function returns the dataclass of the entity selection.

Esta função é principalmente útil no contexto do código genérico.

Exemplo

O seguinte código genérico duplica todas as entidades da entity selection:

  //duplicate_entities method
//duplicate_entities($entity_selection)

#DECLARE ( $entitySelection : 4D.EntitySelection )
var $dataClass : 4D.DataClass
var $entity; $duplicate : 4D.Entity
var $status : Object
$dataClass:=$entitySelection.getDataClass()
For each($entity;$entitySelection)
$duplicate:=$dataClass.new()
$duplicate.fromObject($entity.toObject())
$duplicate[$dataClass.getInfo().primaryKey]:=Null //reset the primary key
$status:=$duplicate.save()
End for each

.getRemoteContextAttributes()

História
ReleaseMudanças
19R5Adicionado

.getRemoteContextAttributes() : Text

ParâmetroTipoDescrição
resultText<-Atributos de contexto conectados à seleção de entidade, separados por uma vírgula

Advanced mode: This function is intended for developers who need to customize ORDA default features for specific configurations. Na maioria dos casos, não necessitará de o utilizar.

Descrição

The .getRemoteContextAttributes() function returns information about the optimization context used by the entity selection.

If there is no optimization context for the entity selection, the function returns an empty Text.

Exemplo

var $ds : 4D. DataStoreImplementation
var $persons : cs. PersonsSelection
var $p : cs. PersonsEntity

var $info : Text
var $text : Text

$ds:=Open datastore(New object("hostname"; "www.myserver.com"); "myDS")

$persons:=$ds. Persons.all()
$text:="" For each ($p; $persons)
$text:=$p.firstname+" lives in "+$p.address.city+" / " End for each

$info:=$persons.getRemoteContextAttributes()
//$info = "firstname,address,address.city"

Veja também

Entity.getRemoteContextAttributes()
.clearAllRemoteContexts()
.getRemoteContextInfo()
.getAllRemoteContexts()
.setRemoteContextInfo()

.isAlterable()

História
ReleaseMudanças
18 R5Adicionado

.isAlterable() : Boolean

ParâmetroTipoDescrição
ResultadosParâmetros<-True se a seleção de entidades for alterável, senão False

Descrição

The .isAlterable() function returns True if the entity selection is alterable, and False if the entity selection is not alterable.

For more information, please refer to Shareable or alterable entity selections.

Exemplo

You are about to display Form.products in a list box to allow the user to add new products. Se quiser ter certeza que é alterável para que o usuário possa adicionar novos produtos sem erro:

If (Not(Form.products.isAlterable()))
Form.products:=Form.products.copy()
End if
...
Form.products.add(Form.product)

.isOrdered()

História
ReleaseMudanças
17Adicionado

.isOrdered() : Boolean

ParâmetroTipoDescrição
ResultadosParâmetros<-True se a seleção de entidade for ordenada, senão False

Descrição

The .isOrdered() function returns True if the entity selection is ordered, and False if it is unordered.

Esta função devolve sempre True quando a selecção da entidade provém de um datastore remoto.

For more information, please refer to Ordered or unordered entity selection.

Exemplo

 var $employees : cs.EmployeeSelection
var $employee : cs.EmployeeEntity
var $isOrdered : Boolean
$employees:=ds.Employee.newSelection(dk keep ordered)
$employee:=ds.Employee.get(714) // Gets the entity with primary key 714

//In an ordered entity selection, we can add the same entity several times (duplications are kept)
$employees.add($employee)
$employees.add($employee)
$employees.add($employee)

$isOrdered:=$employees.isOrdered()
If($isOrdered)
ALERT("The entity selection is ordered and contains "+String($employees.length)+" employees")
End if

.last()

História
ReleaseMudanças
17Adicionado

.last() : 4D.Entity

ParâmetroTipoDescrição
Resultados4D. Entity<-Referência à última entidade da seleção de entidades (Null se a seleção de entidades estiver vazia)

Descrição

The .last() function returns a reference to the entity in last position of the entity selection.

O resultado desta função é similar a:

 $entity:=$entitySel[length-1]

Se a entity selection estiver vazia, a função devolve Null.

Exemplo

 var $entitySelection : cs.EmpSelection
var $entity : cs.EmpEntity
$entitySelection:=ds.Emp.query("salary < :1";50000)
If($entitySelection.length#0)
$entity:=$entitySelection.last()
End if

.length

História
ReleaseMudanças
17Adicionado

.length : Integer

Descrição

The .length property returns the number of entities in the entity selection. Se a entity selection estiver vazia, devolve 0.

Entity selections always have a .length property.

To know the total number of entities in a dataclass, it is recommended to use the getCount() function which is more optimized than the ds.myClass.all().length expression.

Exemplo

 var $vSize : Integer
$vSize:=ds. Employee.query("gender = :1";"male").length
ALERT(String(vSize)+" male employees found.")

.max()

História
ReleaseMudanças
17Adicionado
18 R6Retorna indefinido se uma seleção de entidade for vazia

.max( attributePath : Text ) : any

ParâmetroTipoDescrição
attributePathText->Rota do atributo que se utilizará para o cálculo
Resultadosany<-Maior valor do atributo

Descrição

The .max() function returns the highest (or maximum) value among all the values of attributePath in the entity selection. It actually returns the value of the last entity of the entity selection as it would be sorted in ascending order using the .orderBy() function.

If you pass in attributePath a path to an object property containing different types of values, the .max() function will return the maximum value within the first scalar type in the default 4D type list order (see .sort() description).

.max() returns undefined if the entity selection is empty or attributePath is not found in the object attribute.

Um erro é retornado se:

  • attributePath is a related attribute,
  • attributePath designates an attribute that does not exist in the entity selection dataclass.

Exemplo

Se quisermos encontrar o maior salário entre as funcionárias mulheres:

 var $sel : cs. EmpSelection
var $maxSalary : Real
$sel:=ds. Employee.query("gender = :1";"female")
$maxSalary:=$sel.max("salary")

.min()

História
ReleaseMudanças
17Adicionado
18 R6Retorna indefinido se uma seleção de entidade for vazia

.min( attributePath : Text ) : any

ParâmetroTipoDescrição
attributePathText->Rota do atributo que se utilizará para o cálculo
Resultadosany<-Menor valor do atributo

Descrição

The .min() function returns the lowest (or minimum) value among all the values of attributePath in the entity selection. It actually returns the first entity of the entity selection as it would be sorted in ascending order using the .orderBy() function (excluding null values).

If you pass in attributePath a path to an object property containing different types of values, the .min() function will return the minimum value within the first scalar value type in the type list order (see .sort() description).

.min() returns undefined if the entity selection is empty or attributePath is not found in the object attribute.

Um erro é retornado se:

  • attributePath is a related attribute,
  • attributePath designates an attribute that does not exist in the entity selection dataclass.

Exemplo

Neste exemplo, se quisermos encontrar o menor salário entre todos os funcionários mulheres:

 var $sel : cs. EmpSelection
var $minSalary : Real
$sel:=ds. Employee.query("gender = :1";"female")
$minSalary:=$sel.min("salary")

.minus()

História
ReleaseMudanças
18 R6Support of keepOrder parameter
17Adicionado

.minus( entity : 4D.Entity { ; keepOrder : Integer } ) : 4D.EntitySelection
.minus( entitySelection : 4D.EntitySelection { ; keepOrder : Integer } ) : 4D.EntitySelection

ParâmetroTipoDescrição
entity4D. Entity->Entidade a substrair
entitySelection4D. EntitySelection->seleção de entidade a subtrair
keepOrderInteger->dk keep ordered (integer) to keep the initial order in the resulting entity selection
Resultados4D. EntitySelection<-Nova seleção de entidade ou uma nova referência na seleção de entidade existente

Descrição

The .minus() function excludes from the entity selection to which it is applied the entity or the entities of entitySelection and returns the resulting entity selection.

  • If you pass entity as parameter, the function creates a new entity selection without entity (if entity belongs to the entity selection). If entity was not included in the original entity selection, a new reference to the entity selection is returned.
  • If you pass entitySelection as parameter, the function returns an entity selection containing the entities belonging to the original entity selection without the entities belonging to entitySelection. You can compare ordered and/or unordered entity selections.

By default, if you omit the keepOrder parameter, the resulting entity selection is unordered. If you want to keep the order of the original entity selection (for example if you want to reuse the entity selection in a user interface), pass the dk keep ordered constant in keepOrder. Neste caso, o resultado é uma seleção de entidade ordenada e a ordem da seleção de entidade inicial é mantida

nota

If you pass dk keep ordered in keepOrder and the removed entitySelection contains entities duplicated in the original entity selection, all occurences of the duplicates are removed.

If the original entity selection or both the original entity selection and the entitySelection parameter are empty, an empty entity selection is returned.

If entitySelection is empty or if entity is Null, a new reference to the original entity selection is returned.

Se a entity selection inicial e o parâmetro não forem relacionados com a mesma dataclass, se produz um erro.

Exemplo 1

 var $employees; $result : cs.EmployeeSelection
var $employee : cs.EmployeeEntity

$employees:=ds.Employee.query("lastName = :1";"H@")
// The $employees entity selection contains the entity with primary key 710 and other entities
// for ex. "Colin Hetrick", "Grady Harness", "Sherlock Holmes" (primary key 710)

$employee:=ds.Employee.get(710) // Returns "Sherlock Holmes"

$result:=$employees.minus($employee) //$result contains "Colin Hetrick", "Grady Harness"

Exemplo 2

Se quisermos ter uma seleção de empregados mulheres que se chamam "Jones" que vivem em Nova York:

 var $sel1; $sel2; $sel3 : cs. EmployeeSelection
$sel1:=ds. Employee.query("name =:1";"Jones")
$sel2:=ds. Employee.query("city=:1";"New York")
$sel3:=$sel1.and($sel2).minus(ds. Employee.query("gender='male'"))

Exemplo 3

Em uma interface de usuário se tivermos uma lista que exibe itens em uma ordem específica. Se o usuário selecionar itens na lista para remove-los, a ordem deve ser mantida quando refrescar a lista:

Employee.newSelection(dk keep ordered)
$employee:=ds.

.or()

História
ReleaseMudanças
17Adicionado

.or( entity : 4D.Entity ) : 4D.EntitySelection
.or( entitySelection : 4D.EntitySelection ) : 4D.EntitySelection

ParâmetroTipoDescrição
entity4D. Entity->Entidade a intersectar
entitySelection4D. EntitySelection->Entity selection a intersectar
Resultados4D. EntitySelection<-Nova seleção de entidade ou nova referência à seleção de entidade original

Descrição

The .or() function combines the entity selection with the entity or entitySelection parameter using the logical (not exclusive) OR operator; it returns a new, unordered entity selection that contains all the entities from the entity selection and the parameter.

  • If you pass entity as parameter, you compare this entity with the entity selection. Se a entidade pertencer à selecção de entidades, é devolvida uma nova referência à selecção de entidades. Senão, uma nova seleção de entidade contém a seleção de entidade original e a entidade é retornada.
  • If you pass entitySelection as parameter, you compare entity selections. A new entity selection containing the entities belonging to the original entity selection or entitySelection is returned (or is not exclusive, entities referenced in both selections are not duplicated in the resulting selection).

You can compare ordered and/or unordered entity selections. A seleção resultante é sempre desordenada.

If the original entity selection and the entitySelection parameter are empty, an empty entity selection is returned. If the original entity selection is empty, a reference to entitySelection or an entity selection containing only entity is returned.

If entitySelection is empty or if entity is Null, a new reference to the original entity selection is returned.

Se a entity selection inicial e o parâmetro não forem relacionados com a mesma dataclass, se produz um erro.

Exemplo 1

 var $employees1; $employees2; $result : cs. EmployeeSelection
$employees1:=ds. Employee.query("lastName = :1";"H@") //Returns "Colin Hetrick","Grady Harness"
$employees2:=ds. Employee.query("firstName = :1";"C@") //Returns "Colin Hetrick", "Cath Kidston"
$result:=$employees1.or($employees2) //$result contains "Colin Hetrick", "Grady Harness","Cath Kidston"

Exemplo 2

 var $employees; $result : cs. EmployeeSelection
var $employee : cs. EmployeeEntity
$employees:=ds. Employee.query("lastName = :1";"H@") // Devuelve "Colin Hetrick","Grady Harness", "Sherlock Holmes"
$employee:=ds. Employee.get(686) //a entidade com chave primária 686 não pertence a entity selection $employees
//Coincide com a funcionária "Mary Smith"

$result:=$employees.or($employee) //$result contém "Colin Hetrick", "Grady Harness", "Sherlock Holmes", "Mary Smith"

.orderBy()

História
ReleaseMudanças
17Adicionado

.orderBy( pathString : Text ) : 4D.EntitySelection
.orderBy( pathObjects : Collection ) : 4D.EntitySelection

ParâmetroTipoDescrição
pathStringText->Rota(s) de atributos e instruções de classificação para a entity selection
pathObjectsCollection->Coleção de objetos criterio
Resultados4D. EntitySelection<-Nova entity selection na ordem especificada

Descrição

The .orderBy() function returns a new ordered entity selection containing all entities of the entity selection in the order specified by pathString or pathObjects criteria.

Deve usar um parâmetro critério para definir como as entidades são ordenadas. Dois parâmetros diferentes são compatíveis:

  • pathString (Text) : This parameter contains a formula made of 1 to x attribute paths and (optionally) sort orders, separated by commas. A sintaxe é:
"attributePath1 {desc or asc}, attributePath2 {desc or asc},..."

A ordem na qual os atributos forem passados determina a prioridade de ordenação das entidades. Como padrão, atributos são ordenados em ordem ascendente. Pode definir a ordem de clasificação de uma propriedade na string de critérios, separado da rota da propriedade por um só espaço: passe "asc" para ordenar em ordem ascendente ou "desc" em ordem descendente.

  • pathObjects (collection): each element of the collection contains an object structured in the following way:
{
"propertyPath": string,
"descending": boolean
}

Como padrão, atributos são ordenados em ordem ascendente ("descendente" é false)

Pode adicionar quantos objetos quiser nos critérios da coleção.

Valores null são avaliados como menor que outros valores.

If you pass an invalid attribute path in pathString or pathObject, the function returns an empty entity selection.

Exemplo

// order by formula
$sortedEntitySelection:=$entitySelection.orderBy("firstName asc, salary desc")
$sortedEntitySelection:=$entitySelection.orderBy("firstName")


// order by collection with or without sort orders
$orderColl:=New collection
$orderColl.push(New object("propertyPath";"firstName";"descending";False))
$orderColl.push(New object("propertyPath";"salary";"descending";True))
$sortedEntitySelection:=$entitySelection.orderBy($orderColl)

$orderColl:=New collection
$orderColl.push(New object("propertyPath";"manager.lastName"))

$orderColl.push(New object("propertyPath";"salary"))
$sortedEntitySelection:=$entitySelection.orderBy($orderColl)

.orderByFormula()

História
ReleaseMudanças
17 R6Adicionado

.orderByFormula( formulaString : Text { ; sortOrder : Integer } { ; settings : Object} ) : 4D.EntitySelection
.orderByFormula( formulaObj : Object { ; sortOrder : Integer } { ; settings : Object} ) : 4D.EntitySelection

ParâmetroTipoDescrição
formulaStringText->Formula string
formulaObjObject->Objecto fórmula
sortOrderInteger->dk ascending (default) or dk descending
settingsObject->Parâmetros da fórmula
Resultados4D. EntitySelection<-Nova seleção de entidade ordenada

Descrição

The .orderByFormula() function returns a new, ordered entity selection containing all entities of the entity selection in the order defined through the formulaString or formulaObj and, optionally, sortOrder and settings parameters.

Esta função não modifica a seleção de entidades original.

You can use either a formulaString or a formulaObj parameter:

  • formulaString: you pass a 4D expression such as "Year of(this.birthDate)".
  • formulaObj: pass a valid formula object created using the Formula or Formula from string command.

The formulaString or formulaObj is executed for each entity of the entity selection and its result is used to define the position of the entity in the returned entity selection. O resultado deve ser um tipo ordenavel (booleano, data, número, texto, hora, null).

Um resultado nullé sempre o menor valor.

By default if you omit the sortOrder parameter, the resulting entity selection is sorted in ascending order. Optionnally, you can pass one of the following values in the sortOrder parameter:

ParâmetrosValorComentário
dk ascending0Ordem ascendente (padrão)
dk descending1Ordem descendente

Within the formulaString or formulaObj, the processed entity and thus its attributes are available through the This command (for example, This.lastName).

You can pass parameter(s) to the formula using the args property (object) of the settings parameter: the formula receives the settings.args object in $1.

Exemplo 1

Ordenar estudantes usando uma fórmula fornecida como texto:

 var $es1; $es2 : cs. StudentsSelection
$es1:=ds. Students.query("nationality=:1";"French")
$es2:=$es1.orderByFormula("length(this.lastname)") //ascending by default
$es2:=$es1.orderByFormula("length(this.lastname)";dk descending)

Mesma ordem mas usando objeto fórmula:

 var $es1; $es2 : cs. StudentsSelection
var $formula : Object
$es1:=ds. Students.query("nationality=:1";"French")
$formula:=Formula(Length(This.lastname))
$es2:=$es1.orderByFormula($formula) // ascending by default
$es2:=$es1.orderByFormula($formula;dk descending)

Exemplo 2

A formula is given as a formula object with parameters; settings.args object is received as $1 in the computeAverage method.

In this example, the "marks" object field in the Students dataClass contains students' grades for each subject. Um objeto fórmula é usado para computar a média das notas dos estudantes com coeficientes diferentes para schoolA e schoolB

 var $es1; $es2 : cs.StudentsSelection
var $formula; $schoolA; $schoolB : Object
$es1:=ds.Students.query("nationality=:1";"French")
$formula:=Formula(computeAverage($1))

$schoolA:=New object() //settings object
$schoolA.args:=New object("english";1;"math";1;"history";1) // Coefficients to compute an average

//Order students according to school A criteria
$es2:=$es1.entitySelection.orderByFormula($formula;$schoolA)

$schoolB:=New object() //settings object
$schoolB.args:=New object("english";1;"math";2;"history";3) // Coefficients to compute an average

//Order students according to school B criteria
$es2:=$es1.entitySelection.orderByFormula($formula;dk descending;$schoolB)
  //
// computeAverage method
// -----------------------------
#DECLARE ($coefList : Object) -> $result : Integer
var $subject : Text
var $average; $sum : Integer

$average:=0
$sum:=0

For each($subject;$coefList)
$sum:=$sum+$coefList[$subject]
End for each

For each($subject;This.marks)
$average:=$average+(This.marks[$subject]*$coefList[$subject])
End for each

$result:=$average/$sum

.query()

História
ReleaseMudanças
17 R6Soporte dos Parâmetros Formula
17 R5Suporte dos marcadores para os valores
17Adicionado

.query( queryString : Text { ; ...value : any } { ; querySettings : Object } ) : 4D.EntitySelection
.query( formula : Object { ; querySettings : Object } ) : 4D.EntitySelection

ParâmetroTipoDescrição
queryStringText->Criterios de pesquisa como string
formulaObject->Criterios de pesquisa como objeto fórmula
valueany->Valores a usar para placeholders indexados
querySettingsObject->Opções de pesquisa: parâmetros, atributos, args, allowFormulas, contexto, queryPath,queryPlan
Resultados4D. EntitySelection<-New entity selection made up of entities from entity selection meeting the search criteria specified in queryString or formula

Descrição

The .query() function searches for entities that meet the search criteria specified in queryString or formula and (optionally) value(s) among all the entities in the entity selection, and returns a new object of type EntitySelection containing all the entities that are found. Se aplica carregamento diferido/lazy loading.

Esta função não modifica a seleção de entidades original.

If no matching entities are found, an empty EntitySelection is returned.

For detailed information on how to build a query using queryString, value, and querySettings parameters, please refer to the DataClass .query() function description.

By default if you omit the order by statement in the queryString, the returned entity selection is not ordered. Note entretanto que em modo Cliente Servidor funciona como uma seleção de entidade ordenada (entidades são adicionadas no final da seleção)

Exemplo 1

 var $entitySelectionTemp : cs.EmployeeSelection
$entitySelectionTemp:=ds.Employee.query("lastName = :1";"M@")
Form.emps:=$entitySelectionTemp.query("manager.lastName = :1";"S@")

Exemplo 2

More examples of queries can be found in the DataClass .query() page.

Veja também

.query() for dataclass

.queryPath

História
ReleaseMudanças
17Adicionado

.queryPath : Text

Descrição

The .queryPath property contains a detailed description of the query as it was actually performed by 4D. This property is available for EntitySelection objects generated through queries if the "queryPath":true property was passed in the querySettings parameter of the .query() function.

For more information, refer to the querySettings parameter paragraph in the Dataclass.query() page.

.queryPlan

História
ReleaseMudanças
17Adicionado

.queryPlan : Text

Descrição

The .queryPlan property contains a detailed description of the query just before it is executed (i.e., the planned query). This property is available for EntitySelection objects generated through queries if the "queryPlan":true property was passed in the querySettings parameter of the .query() function.

For more information, refer to the querySettings parameter paragraph in the Dataclass.query() page.

.refresh()

História
ReleaseMudanças
18 R3Adicionado

.refresh()

ParâmetroTipoDescrição
Não exige nenhum parâmetro

Descrição

This function only works with a remote datastore (client / server or Open datastore connection).

The .refresh() function immediately "invalidates" the entity selection data in the local ORDA cache so that the next time 4D requires the entity selection, it will be reloaded from the database.

Como padrão, a cache ORDA local é invaidade depois de 30 segundos. No contexto de aplicações cliente/servidor usando ORDA e a linguagem clássica, este método permite assegurar que a aplicação remota vai sempre funcionar com os últimos dados.

Exemplo 1

Neste exemplo, clássico e ORDA modifica os mesmos dados simultaneamente.

 //On a 4D remote

var $selection : cs.StudentsSelection
var $student : cs.StudentsEntity

$selection:=ds.Students.query("lastname=:1";"Collins")
//The first entity is loaded in the ORDA cache
$student:=$selection.first()

//Update with classic 4D, ORDA cache is not aware of if
QUERY([Students];[Students]lastname="Collins")
[Students]lastname:="Colin"
SAVE RECORD([Students])

//to get the latest version, the ORDA cache must be invalidated
$selection.refresh()
// Even if cache is not expired, the first entity is reloaded from disk
$student:=$selection.first()

//$student.lastname contains "Colin"

Exemplo 2

Uma list box exibe a seleção de entidade Form.students e vários clientes trabalham nele.

// Método de formulário:
Case of
:(Form event code=On Load)
Form.students:=ds. Students.all()
End case
//
//
// Em client #1, o usuário carrega atualiza e salva a primeira entidade
// Em client #2, o usuário carrega atualiza e salva a mesma entidade
//
//
// Em client #1:
Form.students.refresh() // Invalida a cache ORDA para a seleção de entidade Form.students
// O conteúdo list box é atualizado na database com atuaização feita pelo client #2

.selected()

História
ReleaseMudanças
19 R3Adicionado

.selected( selectedEntities : 4D.EntitySelection ) : Object

ParâmetroTipoDescrição
Parâmetros4D. EntitySelection->Seleção de entidade com entidades para qual saber o ranking da seleção de entidade
ResultadosObject<-Intervalos da seleção de entidade da seleção de entidade

Descrição

The .selected() function returns an object describing the position(s) of selectedEntities in the original entity selection.

Esta função não modifica a seleção de entidades original.

Pass in the selectedEntities parameter an entity selection containing entities for which you want to know the position in the original entity selection. selectedEntities must be an entity selection belonging to the same dataclass as the original entity selection, otherwise an error 1587 - "The entity selection comes from an incompatible dataclass" is raised.

Resultados

O objeto retornado contém as propriedades abaixo:

PropriedadeTipoDescrição
rangesCollectionColeção de objetos intervalos
ranges[].startIntegerPrimeiro indice de entidade do intervalo
ranges[].endIntegerÚltimo indice de entidade no intervalo.

If a ranges property contains a single entity, start = end. Indice começa em 0

The function returns an empty collection in the ranges property if the original entity selection or the selectedEntities entity selection is empty.

Exemplo

var $invoices; $cashSel; $creditSel : cs.Invoices
var $result1; $result2 : Object

$invoices:=ds.Invoices.all()

$cashSelection:=ds.Invoices.query("payment = :1"; "Cash")
$creditSel:=ds.Invoices.query("payment IN :1"; New collection("Cash"; "Credit Card"))

$result1:=$invoices.selected($cashSelection)
$result2:=$invoices.selected($creditSel)

//$result1 = {ranges:[{start:0;end:0},{start:3;end:3},{start:6;end:6}]}
//$result2 = {ranges:[{start:0;end:1},{start:3;end:4},{start:6;end:7}]}

.slice()

História
ReleaseMudanças
17Adicionado

.slice( startFrom : Integer { ; end : Integer } ) : 4D.EntitySelection

ParâmetroTipoDescrição
startFromInteger->Indice para iniciar a operação em (incluido)
endInteger->Final do índice (não incluído)
Resultados4D. EntitySelection<-Nova seleção de entidade contendo entidades fatiadas (cópia superficial)

Descrição

The .slice() function returns a portion of an entity selection into a new entity selection, selected from the startFrom index to the end index (end is not included) or to the last entity of the entity selection. Este método devolve uma cópia superficial da selecção de entidades (utiliza as mesmas referências de entidades).

Esta função não modifica a seleção de entidades original.

The returned entity selection contains the entities specified by startFrom and all subsequent entities up to, but not including, the entity specified by end. If only the startFrom parameter is specified, the returned entity selection contains all entities from startFrom to the last entity of the original entity selection.

  • If startFrom < 0, it is recalculated as startFrom:=startFrom+length (it is considered as the offset from the end of the entity selection). If the calculated value < 0, startFrom is set to 0.
  • If startFrom >= length, the function returns an empty entity selection.
  • If end < 0, it is recalculated as end:=end+length.
  • If end < startFrom (passed or calculated values), the method does nothing.

Se a seleção de entidade contém entidades que foram abandonadas, também serão retornadas.

Exemplo 1

Se quiser obter uma seleção das primeiras 9 entidades da seleção de entidade:

var $sel; $sliced : cs.EmployeeSelection
$sel:=ds.Employee.query("salary > :1";50000)
$sliced:=$sel.slice(0;9) //

Exemplo 2

Assuming we have ds. Employee.all().length = 10

var $slice : cs.EmployeeSelection


$slice:=ds.Employee.all().slice(-1;-2) //tries to return entities from index 9 to 8, but since 9 > 8, returns an empty entity selection

.sum()

História
ReleaseMudanças
17Adicionado

.sum( attributePath : Text ) : Real

ParâmetroTipoDescrição
attributePathText->Rota do atributo que se utilizará para o cálculo
ResultadosReal<-Soma dos valores da seleção de entidade

Descrição

The .sum() function returns the sum for all attributePath values in the entity selection.

.sum() returns 0 if the entity selection is empty.

A soma só pode ser feita em valores do tipo de número. If the attributePath is an object property, only numerical values are taken into account for the calculation (other value types are ignored). In this case, if attributePath leads to a property that does not exist in the object or does not contain any numeric values, .sum() returns 0.

Um erro é retornado se:

  • attributePath is not a numerical or an object attribute,
  • attributePath is a related attribute,
  • attributePath is not found in the entity selection dataclass.

Exemplo

var $sel : cs.EmployeeSelection
var $sum : Real

$sel:=ds.Employee.query("salary < :1";20000)
$sum:=$sel.sum("salary")

.toCollection()

História
ReleaseMudanças
17Adicionado

.toCollection( { options : Integer { ; begin : Integer { ; howMany : Integer } } ) : Collection
.toCollection( filterString : Text {; options : Integer { ; begin : Integer { ; howMany : Integer }}} ) : Collection
.toCollection( filterCol : Collection {; options : Integer { ; begin : Integer { ; howMany : Integer }}} ) : Collection

ParâmetroTipoDescrição
filterStringText->String com caminho(s) de atributo(s) de entidade a extrair
filterColCollection->Coleção de caminho(s) de atributo(s) de entidade a extrair
optionsInteger->dk with primary key: adds the primary key
dk with stamp: adds the stamp
beginInteger->Designa o índice inicial
howManyInteger->Número de entidades a extrair
ResultadosCollection<-Colecção de objectos contendo atributos e valores de selecção de entidades

Descrição

The .toCollection() function creates and returns a collection where each element is an object containing a set of properties and values corresponding to the attribute names and values for the entity selection.

Se nenhum parâmetro de filtro for passado ou se o primeiro parâmetro contiver uma cadeia vazia ou "*", todos os atributos são extraídos. Attributes with kind property as "relatedEntity" are extracted with the simple form: an object with property __KEY (primary key). Atributos com propriedade tipo como "Entidades relacionadas" não são extraídos.

Ou, pode designar os atributos da entidade a extrair utilizando um parâmetro de filtro. Pode usar um destes dois filtros:

  • filterString --a string with property paths separated with commas: "propertyPath1, propertyPath2, ...".
  • filterCol --a collection of strings containing property paths: ["propertyPath1","propertyPath2",...]

If a filter is specified for an attribute of the relatedEntity kind:

  • propertyPath = "relatedEntity" -> it is extracted with simple form
  • propertyPath = "relatedEntity.*" -> all the properties are extracted
  • propertyPath = "relatedEntity.propertyName1, relatedEntity.propertyName2, ..." -> só se extraem essas propriedades

If a filter is specified for an attribute of the relatedEntities kind:

  • propertyPath = "relatedEntities.*" -> all the properties are extracted
  • propertyPath = "relatedEntities.propertyName1, relatedEntities.propertyName2, ..." -> só se extraem essas propriedades

In the options parameter, you can pass the dk with primary key and/or dk with stamp selector(s) to add the entity's primary keys and/or stamps in extracted objects.

Aviso

Se utilizar outro atributo que não a chave primária como o atributo Um numa relação, o valor deste atributo será escrito na propriedade "__KEY". Keep in mind that it is recommended to use the primary key as One attribute in your relations, especially when you use .toCollection() and .fromCollection() functions.

The begin parameter allows you to indicate the starting index of the entities to extract. Pode passar qualquer valor entre 0 e o comprimento-1 da selecção da entidade.

The howMany parameter lets you specify the number of entities to extract, starting with the one specified in begin. Dropped entities are not returned but are taken into account according to howMany. For example, if howMany= 3 and there is 1 dropped entity, only 2 entities are extracted.

If howMany > length of the entity selection, the method returns (length - begin) objects.

Uma colecção vazia é devolvida se:

  • a selecção da entidade está vazia, ou
  • begin is greater than the length of the entity selection.

Exemplo 1

A estrutura abaixo será usada nos exemplos desta seção:

Exemplo sem filtro ou parâmetro de opções:

 var $employeesCollection : Collection
var $employees : cs.EmployeeSelection

$employeesCollection:=New collection
$employees:=ds.Employee.all()
$employeesCollection:=$employees.toCollection()

Retorna:

[
{
"ID": 416,
"firstName": "Gregg",
"lastName": "Wahl",
"salary": 79100,
"birthDate": "1963-02-01T00:00:00.000Z",
"woman": false,
"managerID": 412,
"employerID": 20,
"photo": "[object Picture]",
"extra": null,
"employer": {
"__KEY": 20
},
"manager": {
"__KEY": 412
}
},
{
"ID": 417,
"firstName": "Irma",
"lastName": "Durham",
"salary": 47000,
"birthDate": "1992-06-16T00:00:00.000Z",
"woman": true,
"managerID": 412,
"employerID": 20,
"photo": "[object Picture]",
"extra": null,
"employer": {
"__KEY": 20
},
"manager": {
"__KEY": 412
}
}
]

Exemplo 2

Exemplo com opções:

var $employeesCollection : Collection
var $employees : cs. EmployeeSelection

$employeesCollection:=New collection
$employees:=ds. Employee.all()
$employeesCollection:=$employees.toCollection("";dk with primary key+dk with stamp)

Retorna:

[
{
"__KEY": 416,
"__STAMP": 1,
"ID": 416,
"firstName": "Gregg",
"lastName": "Wahl",
"salary": 79100,
"birthDate": "1963-02-01T00:00:00.000Z",
"woman": false,
"managerID": 412,
"employerID": 20,
"photo": "[object Picture]",
"extra": null,
"employer": {
"__KEY": 20
},
"manager": {
"__KEY": 412
}
},
{
"__KEY": 417,
"__STAMP": 1,
"ID": 417,
"firstName": "Irma",
"lastName": "Durham",
"salary": 47000,
"birthDate": "1992-06-16T00:00:00.000Z",
"woman": true,
"managerID": 412,
"employerID": 20,
"photo": "[object Picture]",
"extra": null,
"employer": {
"__KEY": 20
},
"manager": {
"__KEY": 412
}
}]

Exemplo 3

Exemplo com fatiagem e filtragem nas propriedades:

var $employeesCollection; $filter : Collection
var $employees : cs. EmployeeSelection

$employeesCollection:=New collection
$filter:=New collection
$filter.push("firstName")
$filter.push("lastName")

$employees:=ds. Employee.all()
$employeesCollection:=$employees.toCollection($filter;0;0;2)

Retorna:

[
{
"firstName": "Gregg",
"lastName": "Wahl"
},
{
"firstName": "Irma",
"lastName": "Durham"
}
]

Exemplo

Example with relatedEntity type with simple form:

var $employeesCollection : Collection
$employeesCollection:=New collection
$employeesCollection:=$employees.toCollection("firstName,lastName,employer")

retorna:

[
{
"firstName": "Gregg",
"lastName": "Wahl",
"employer": {
"__KEY": 20
}
},
{
"firstName": "Irma",
"lastName": "Durham",
"employer": {
"__KEY": 20
}
},
{
"firstName": "Lorena",
"lastName": "Boothe",
"employer": {
"__KEY": 20
}
}
]

Exemplo 2

Example with filterCol parameter:

var $employeesCollection; $coll : Collection
$employeesCollection:=New collection
$coll:=New collection("firstName";"lastName")
$employeesCollection:=$employees.toCollection($coll)

Retorna:

[
{
"firstName": "Joanna",
"lastName": "Cabrera"
},
{
"firstName": "Alexandra",
"lastName": "Coleman"
}
]

Exemplo 6

Exemplo com extracção de todas as propriedades de relatedEntity:

var $employeesCollection; $coll : Collection
$employeesCollection:=New collection
$coll:=New collection
$coll.push("firstName")
$coll.push("lastName")
$coll.push("employer.*")
$employeesCollection:=$employees.toCollection($coll)

Retorna:

[
{
"firstName": "Gregg",
"lastName": "Wahl",
"employer": {
"ID": 20,
"name": "Irma",
"lastName": "Durham",
"employer": {
"ID": 20,
"name": "Lorena",
"lastName": "Boothe",
"employer": {
"ID": 20,
"name": "India Astral Secretary",
"creationDate": "1984-08-25T00:00:00.000Z",
"revenues": 12000000,
"extra": null
}
}
]

Exemplo 3

Exemplo com extracção de algumas propriedades de uma relatedEntity:

var $employeesCollection : Collection
$employeesCollection:=New collection
$employeesCollection:=$employees.toCollection("firstName, lastName, employer.name")
[
{
"firstName": "Gregg",
"lastName": "Wahl",

"employer": {
"name": "Irma",
"lastName": "Durham",
"employer": {
"name": "Lorena",
"lastName": "Boothe",
"employer": {
"name": "India Astral Secretary"
}
}]

Exemplo 8

Example with extraction of some properties of relatedEntities:

 var $employeesCollection : Collection
$employeesCollection:=New collection
$employeesCollection:=$employees.toCollection("firstName, lastName, directReports.firstName")

Retorna:

[
{
"firstName": "Gregg",
"lastName": "Wahl",
"directReports": []
},
{
"firstName": "Mike",
"lastName": "Phan",
"directReports": [
{
"firstName": "Gary"
},
{
"firstName": "Sadie"
},
{
"firstName": "Christie"
}
]
},
{
"firstName": "Gary",

"lastName": "Reichert",
"directReports": [
{
"firstName": "Rex"
},
{
"firstName": "Jenny"
},
{
"firstName": "Lowell"
}
]
}]

Exemplo 9

Example with extraction of all properties of relatedEntities:

var $employeesCollection : Collection
$employeesCollection:=New collection
$employeesCollection:=$employees.toCollection("firstName, lastName, directReports.*")

[
{
"firstName": "Gregg",
"lastName": "Wahl",
"directReports": []
},
{
"firstName": "Mike",
"lastName": "Phan",
"directReports": [
{
"ID": 425,
"firstName": "Gary",
"lastName": "Reichert",
"salary": 65800,
"birthDate": "1957-12-23T00:00:00.000Z",
"woman": false,
"managerID": 424,
"employerID": 21,
"photo": "[object Picture]",
"extra": null,
"employer": {
"__KEY": 21
},
"manager": {
"__KEY": 424
}
},
{
"ID": 426,
"firstName": "Sadie",
"lastName": "Gallant",
"salary": 35200,
"birthDate": "2022-01-03T00:00:00.000Z",
"woman": true,
"managerID": 424,
"employerID": 21,
"photo": "[object Picture]",
"extra": null,
"employer": {
"__KEY": 21
},
"manager": {
"__KEY": 424
}
}
]
},
{
"firstName": "Gary",
"lastName": "Reichert",
"directReports": [
{
"ID": 428,
"firstName": "Rex",
"lastName": "Chance",
"salary": 71600,
"birthDate": "1968-08-09T00:00:00.000Z",
"woman": false,

"managerID": 425,
"employerID": 21,
"photo": "[object Picture]",
"extra": null,
"employer": {
"__KEY": 21
},
"manager": {
"__KEY": 425
}
},
{
"ID": 429,
"firstName": "Jenny",
"lastName":