Skip to content

ForeignKeyType

Wyatt Greenway edited this page Dec 13, 2022 · 18 revisions

class ForeignKeyType extends Type 📜

FOREIGN_KEY type.

This represents a foreign key to another column. It takes on the type of the column it points to. For example, if it points to an INTEGER column, then it will also be the same type of integer.

Foreign keys are one of the ways Mythix ORM knows that models are related, along with the ModelType and ModelsType virtual types. The "target" field must be a fully qualified field name. A fully qualified field name is a name that is also prefixed by the model that owns it. For example, 'User:firstName' would be a fully qualified field name, but 'firstName' would not be.

Client-side storage for this field will be backed by the same type as the field the foreign key targets.

Example:

  • class Role extends Model {
      static fields = {
        userID: {
          type: Types.FOREIGN_KEY('User:id', {
            onDelete: 'CASCADE',
            onUpdate: 'CASCADE',
          }),
          allowNull: false,
        },
        roleMetaID: {
          type: Types.FOREIGN_KEY({
            modelName: 'RoleMeta',
            fieldName: 'id',
            onDelete: 'CASCADE',
            onUpdate: 'CASCADE',
          }),
          allowNull: false,
        },
      };
    }

See also: Type

method ForeignKeyType::castToType(
    context: CastToTypeContext,
): any
📜

Cast provided value to underlying type.

This will cast the incoming value to the underlying type of this field, which is the type of the field that it targets.

See Type.castToType for a more detailed description.

Arguments:

Return value: any

Return the incoming value, cast to this type. null and undefined are simply returned without casting.


method ForeignKeyType::constructor(
    fullyQualifiedName: string | object,
    options?: object,
): ForeignKeyType
📜

Construct a new ForeignKeyType type.

This constructor has two call patterns. First, it can be called the shorthand way with a string (a fully qualified field name) as the first argument, and the field options as the second argument. Or, you can simply pass a single options argument, that must contain a modelName and fieldName property that are strings.

Interface:

  • interface ForeignKeyTypeOptions {
      // A direct field from a model, used for the target field
      // directly. i.e. `Field: User.fields.id`.
      // If this is present and valid then it
      // will supersede the `modelName` and `fieldName`
      // properties.
      Field?: Field;
    
      // The model name that owns the target field
      modelName?: string;
    
      // The field name of the target field on the
      // target `modelName`.
      fieldName?: string;
    
      // onDelete specifies what action to take when
      // a row in the target table is deleted.
      onDelete?: 'CASCADE' | 'SET NULL' | 'NO ACTION' | 'SET DEFAULT' | 'RESTRICT'
    
      // onUpdate specifies what action to take when
      // a row in the target table is updated
      // (specifically the target column).
      onUpdate?: 'CASCADE' | 'SET NULL' | 'NO ACTION' | 'SET DEFAULT' | 'RESTRICT'
    }

Arguments:

  • fullyQualifiedName: string | object

    1. The fully qualified name of the target field as a string (i.e. 'User:id'), optionally followed an options argument, or 2) the one and only options argument requiring modelName and fieldName properties.
  • options?: object

    If fullyQualifiedName is defined as a string, then this will be the options to the field.

Return value: ForeignKeyType

A new instance of the ForeignKeyType type.


method ForeignKeyType::getOptions(): object 📜

Get the options that were passed to the ForeignKeyType on creation.

Return value: object

The options object that was given to the field.


method ForeignKeyType::getTargetField(
    connection?: Connection,
): Field
📜

Fetch the target field. You can always access the owning model via the field.Model property on the field.

Notes:

  • If this is called before any model has been initialized, or before a connection has been bound to your models, then you must provide a connection or this method will fail.

Arguments:

  • connection?: Connection

    A database connection, which will be used to fiend the target field.

Return value: Field

The target field from the target model.


method ForeignKeyType::getTargetFieldName(
    connection?: Connection,
): string
📜

Fetch the target field's name.

Notes:

  • If this is called before any model has been initialized, or before a connection has been bound to your models, then you must provide a connection or this method will fail.

Arguments:

  • connection?: Connection

    A database connection, which will be used to fiend the target field.

Return value: string

The target field's name.


method ForeignKeyType::getTargetModel(
    connection?: Connection,
): ModelClass
📜

Fetch the target model, which is the model owning the target field.

Notes:

  • If this is called before any model has been initialized, or before a connection has been bound to your models, then you must provide a connection or this method will fail.

Arguments:

  • connection?: Connection

    A database connection, which will be used to fiend the target field and owning model.

Return value: ModelClass

The target field's owning model.


method ForeignKeyType::getTargetModelName(
    connection?: Connection,
): string
📜

Fetch the name of target model, which is the model owning the target field.

Notes:

  • If this is called before any model has been initialized, or before a connection has been bound to your models, then you must provide a connection or this method will fail.

Arguments:

  • connection?: Connection

    A database connection, which will be used to fiend the target field and owning model.

Return value: string

The target field's owning model name.


method ForeignKeyType::initialize(
    connection: Connection,
    self: Model,
): undefined
📜

Initialize a model instance against this type.

Initialize is called whenever a model instance is created. Note that the type instance is shared across all model instances. initialize is still called for every model instance that is created however, because the type class can modify the model it exists on. For example, the ModelType and ModelsType types inject custom relational methods onto each model instance.

This specific initialize for the ForeignKeyType only runs once however. The first owning model instance that is created will call this method, and at that point the target field will be looked up and found. After this first lookup, the target field will be cached for all future model instances of the same type.

Arguments:

  • connection: Connection

    The database connection of the calling model instance.

  • self: Model

    The actual model instance that is calling this method.

Return value: undefined


method ForeignKeyType::isValidValue(
    value: any,
): boolean
📜

Check if the provided value is valid.

This will check if the provided value valid. It does so by calling the isValidValue of the type that it inherits from its target field.

Arguments:

  • value: any

    The value to check.

Return value: boolean


method ForeignKeyType::parseOptionsAndCheckForErrors(
    SourceModel: ModelClass,
    sourceField,
    connection: Connection,
): { Model: ModelClass, Field: Field }
📜

This is called when the field is first initialized on any model instance. It will verify the options provided to the field, and ensure that it can find the target field requested. If it can't find the target field requested for any reason, then it will throw an exception.

Arguments:

  • SourceModel: ModelClass

    The source model (model owning this foreign key field).

  • sourceField

    The source field (the field containing this foreign key type).

  • connection: Connection

    The database connection. This is needed to fetch the target field and model.

Return value: { Model: ModelClass, Field: Field }

Return the target model and field.


static method ForeignKeyType::getDisplayName(): string 📜

Get the "display" name for this type.

This method is called from Model.toString when stringifying the model for representation.

Notes:

  • This is also an instance method that can be called from an instance of the type.

Return value: string

Return the string value 'FOREIGN_KEY'


static method ForeignKeyType::isForeignKey(): boolean 📜

Check if this is a foreign key type.

There are multiple different "type checking" static methods that exist for all field types. This is one of them. It checks if the type class is a foreign key type. This returns true for FOREIGN_KEY.

Return value: boolean

Return true, as the FOREIGN_KEY type is a foreign key field.


method ForeignKeyType::toString(
    connection?: Connection,
): string
📜

Stringify the type itself. This will be the type of the target field.

If a connection argument is provided, then this will go through the connection to generate the type for the underlying database. If no connection is provided, then a "standard" SQL type will be returned for target field type instead.

Arguments:

  • connection?: Connection

    An optional connection. If provided, send this type through Type.toConnectionType to have the connection itself generate the underlying type for the database. If connection is not provided, then this will simply return a "standard" generic matching SQL type of the target field type.

Return value: string



Clone this wiki locally