Repository: jdkandersson/OpenAlchemy

Issue:
Generated foreign key columns use table name instead of property name
According to the docs:

> When OpenAlchemy constructs the foreign key for you, the name of the property is made up of the name of the property referencing the object (division in the previous example) combined with the name of the property in the foreign key constraint (id in the previous example). These two values are combined as follows: `“<reference property name>_<foreign key column name>”` (division_id in the previous example).

However,  it appears to be using `<foreign key table name>_<foreign key column name>` which causes problems if a schema has two properties which reference the same object.   

Example:

```
Supervisor:
  type: object
  x-tablename: supervisor
  properties:
    id:
      type: integer
      description: Unique identifier for the supervisor.
      example: 0
      x-primary-key: true
      x-autoincrement: true
      readOnly: true
Employee:
  type: object
  x-tablename: employee
  properties:
    id:
      type: integer
      description: Unique identifier for the employee.
      example: 0
      x-primary-key: true
      x-autoincrement: true
      readOnly: true
    primary_supervisor:
      $ref: "#/components/schemas/Supervisor"
    secondary_supervisor:
      $ref: "#/components/schemas/Supervisor"
```

When I generate the Base using init_yaml and create the tables using Base.metadata.create_all(engine) I'm only seeing a single foreign key column in the employee table called `supervisor_id `instead of two separate columns called `primary_supervisor_id ` and `secondary_supervisor_id`. 

Is this the expected behavior?


Discussion:

Patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0a98b9da..ec07c964 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,7 @@
 ## Version _next_
 
 - Add support for generic JSON data for properties.
+- Fix bug where the name of the foreign key column was based on the table name and not the property name.
 
 ## Version 1.2.0 - 2020-06-08
 
diff --git a/README.md b/README.md
index af8023d8..82e0faf6 100644
--- a/README.md
+++ b/README.md
@@ -5,7 +5,7 @@ Translates an OpenAPI schema to SQLAlchemy models.
 ## Installation
 ```bash
 python -m pip install OpenAlchemy
-# To be able to load yaml file
+# To be able to load YAML file
 python -m pip install OpenAlchemy[yaml]
 ```
 
diff --git a/open_alchemy/column_factory/array_ref/foreign_key.py b/open_alchemy/column_factory/array_ref/foreign_key.py
index 7adafd9e..c4a60588 100644
--- a/open_alchemy/column_factory/array_ref/foreign_key.py
+++ b/open_alchemy/column_factory/array_ref/foreign_key.py
@@ -13,6 +13,7 @@ from .. import object_ref
 def set_(
     *,
     ref_model_name: str,
+    logical_name: str,
     model_schema: types.Schema,
     schemas: types.Schemas,
     fk_column: str,
@@ -34,6 +35,7 @@ def set_(
 
     Args:
         ref_model_name: The name of the referenced model.
+        logical_name: The logical name of the array reference property.
         model_schema: The schema which contains the one to many relationship.
         schemas: All the model schemas used to look for the referenced model and to
             resolve any $ref.
@@ -51,8 +53,13 @@ def set_(
     ref_schema = helpers.all_of.merge(schema=ref_schema, schemas=schemas)
 
     # Calculate foreign key artifacts
+    tablename = helpers.peek.tablename(schema=model_schema, schemas={})
+    fk_input_logical_name = f"{tablename}_{logical_name}"
     fk_logical_name, fk_artifacts = object_ref.foreign_key.gather_artifacts(
-        model_schema=model_schema, schemas=schemas, fk_column=fk_column
+        model_schema=model_schema,
+        logical_name=fk_input_logical_name,
+        schemas=schemas,
+        fk_column=fk_column,
     )
 
     # Check whether the foreign key has already been defined in the referenced model
diff --git a/open_alchemy/column_factory/array_ref/link.py b/open_alchemy/column_factory/array_ref/link.py
index 57f3e36a..d35cd5df 100644
--- a/open_alchemy/column_factory/array_ref/link.py
+++ b/open_alchemy/column_factory/array_ref/link.py
@@ -28,6 +28,7 @@ def construct(
     if artifacts.relationship.secondary is None:
         _foreign_key.set_(
             ref_model_name=artifacts.relationship.model_name,
+            logical_name=artifacts.logical_name,
             model_schema=model_schema,
             schemas=schemas,
             fk_column=artifacts.fk_column,
diff --git a/open_alchemy/column_factory/object_ref/artifacts.py b/open_alchemy/column_factory/object_ref/artifacts.py
index 7ff990b4..8b29aa27 100644
--- a/open_alchemy/column_factory/object_ref/artifacts.py
+++ b/open_alchemy/column_factory/object_ref/artifacts.py
@@ -55,6 +55,7 @@ def gather(
 
     return types.ObjectArtifacts(
         spec=intermediary_obj_artifacts.ref_schema,
+        logical_name=logical_name,
         fk_column=intermediary_obj_artifacts.fk_column_name,
         relationship=types.RelationshipArtifacts(
             model_name=intermediary_obj_artifacts.ref_model_name,
diff --git a/open_alchemy/column_factory/object_ref/foreign_key.py b/open_alchemy/column_factory/object_ref/foreign_key.py
index 3d123fe6..f7df42fb 100644
--- a/open_alchemy/column_factory/object_ref/foreign_key.py
+++ b/open_alchemy/column_factory/object_ref/foreign_key.py
@@ -91,6 +91,7 @@ def check_required(
 def gather_artifacts(
     *,
     model_schema: types.Schema,
+    logical_name: str,
     schemas: types.Schemas,
     fk_column: str,
     required: typing.Optional[bool] = None,
@@ -106,6 +107,7 @@ def gather_artifacts(
 
     Args:
         model_schema: The schema of the referenced model.
+        logical_name: The logical name of the property with the object reference.
         schemas: All model schemas used to resolve any $ref.
         fk_column: The name of the foreign key column.
         required: Whether the foreign key is constructed for a property that is
@@ -151,7 +153,7 @@ def gather_artifacts(
     )
 
     # Construct return values
-    logical_name = f"{tablename}_{fk_column}"
+    return_logical_name = f"{logical_name}_{fk_column}"
     artifacts = types.ColumnArtifacts(
         open_api=types.OpenAPiColumnArtifacts(
             type=fk_type,
@@ -164,7 +166,7 @@ def gather_artifacts(
             foreign_key=f"{tablename}.{fk_column}"
         ),
     )
-    return logical_name, artifacts
+    return return_logical_name, artifacts
 
 
 def gather_artifacts_helper(
@@ -189,6 +191,7 @@ def gather_artifacts_helper(
     """
     return gather_artifacts(
         model_schema=obj_artifacts.spec,
+        logical_name=obj_artifacts.logical_name,
         schemas=schemas,
         fk_column=obj_artifacts.fk_column,
         required=required,
diff --git a/open_alchemy/types.py b/open_alchemy/types.py
index 0acffbf5..4a1063a4 100644
--- a/open_alchemy/types.py
+++ b/open_alchemy/types.py
@@ -4,10 +4,14 @@ import dataclasses
 import datetime
 import typing
 
-try:
-    from typing import TypedDict, Literal, Protocol
+try:  # pragma: no cover
+    from typing import TypedDict
+    from typing import Literal
+    from typing import Protocol
 except ImportError:  # pragma: no cover
-    from typing_extensions import TypedDict, Literal, Protocol  # type: ignore
+    from typing_extensions import TypedDict  # type: ignore
+    from typing_extensions import Literal  # type: ignore
+    from typing_extensions import Protocol  # type: ignore
 
 Schema = typing.Dict[str, typing.Any]
 Schemas = typing.Dict[str, Schema]
@@ -175,6 +179,7 @@ class ObjectArtifacts:
     """Artifacts retrieved from object schema."""
 
     spec: Schema
+    logical_name: str
     fk_column: str
     relationship: RelationshipArtifacts
     nullable: typing.Optional[bool] = None
diff --git a/setup.py b/setup.py
index da7cede2..8ff089fd 100644
--- a/setup.py
+++ b/setup.py
@@ -48,7 +48,7 @@ setuptools.setup(
             "pydocstyle",
             "black",
             "pre-commit",
-            "isort",
+            "isort<5.0.0",
             "PyYAML",
             "Sphinx",
             "doc8",


Test patch:
diff --git a/tests/examples/test_example_specs.py b/tests/examples/test_example_specs.py
index e4a0de90..e1480018 100644
--- a/tests/examples/test_example_specs.py
+++ b/tests/examples/test_example_specs.py
@@ -214,7 +214,7 @@ def test_table_args(engine, filename, model_name, sql, expected_contents):
 @pytest.mark.parametrize(
     "filename, model_names, attrs",
     [
-        (
+        pytest.param(
             "relationship/many_to_one/example-spec.yml",
             ("Employee", "Division"),
             {
@@ -222,8 +222,9 @@ def test_table_args(engine, filename, model_name, sql, expected_contents):
                 "name": "employee 1",
                 "division": {"id": 12, "name": "division 1"},
             },
+            id="relationship-many-to-one",
         ),
-        (
+        pytest.param(
             "relationship/many_to_one/backref-example-spec.yml",
             ("Employee", "Division"),
             {
@@ -231,8 +232,9 @@ def test_table_args(engine, filename, model_name, sql, expected_contents):
                 "name": "employee 1",
                 "division": {"id": 12, "name": "division 1"},
             },
+            id="relationship-many-to-one-backref",
         ),
-        (
+        pytest.param(
             "relationship/many_to_one/custom-foreign-key-example-spec.yml",
             ("Employee", "Division"),
             {
@@ -240,8 +242,9 @@ def test_table_args(engine, filename, model_name, sql, expected_contents):
                 "name": "employee 1",
                 "division": {"id": 12, "name": "division 1"},
             },
+            id="relationship-many-to-one-custom-foreign-key",
         ),
-        (
+        pytest.param(
             "relationship/many_to_one/not-nullable-example-spec.yml",
             ("Employee", "Division"),
             {
@@ -249,8 +252,9 @@ def test_table_args(engine, filename, model_name, sql, expected_contents):
                 "name": "employee 1",
                 "division": {"id": 12, "name": "division 1"},
             },
+            id="relationship-many-to-one-not-nullable",
         ),
-        (
+        pytest.param(
             "relationship/one_to_many/example-spec.yml",
             ("Division", "Employee"),
             {
@@ -258,8 +262,9 @@ def test_table_args(engine, filename, model_name, sql, expected_contents):
                 "name": "division 1",
                 "employees": [{"id": 12, "name": "employee 1"}],
             },
+            id="relationship-one-to-many",
         ),
-        (
+        pytest.param(
             "relationship/one_to_one/example-spec.yml",
             ("Employee", "PayInfo"),
             {
@@ -267,8 +272,9 @@ def test_table_args(engine, filename, model_name, sql, expected_contents):
                 "name": "employee 1",
                 "pay_info": {"id": 12, "account_number": "account 1"},
             },
+            id="relationship-one-to-one",
         ),
-        (
+        pytest.param(
             "relationship/many_to_many/example-spec.yml",
             ("Employee", "Project"),
             {
@@ -276,17 +282,9 @@ def test_table_args(engine, filename, model_name, sql, expected_contents):
                 "name": "employee 1",
                 "projects": [{"id": 12, "name": "project 1"}],
             },
+            id="relationship-many-to-many",
         ),
     ],
-    ids=[
-        "relationship-many-to-one",
-        "relationship-many-to-one-backref",
-        "relationship-many-to-one-custom-foreign-key",
-        "relationship-many-to-one-not-nullable",
-        "relationship-one-to-many",
-        "relationship-one-to-one",
-        "relationship-many-to-many",
-    ],
 )
 @pytest.mark.example
 def test_relationship(engine, sessionmaker, filename, model_names, attrs):
diff --git a/tests/open_alchemy/column_factory/array_ref/test_foreign_key.py b/tests/open_alchemy/column_factory/array_ref/test_foreign_key.py
index e9445749..c2992a14 100644
--- a/tests/open_alchemy/column_factory/array_ref/test_foreign_key.py
+++ b/tests/open_alchemy/column_factory/array_ref/test_foreign_key.py
@@ -23,6 +23,7 @@ def test_schemas_missing():
     with pytest.raises(exceptions.MalformedRelationshipError):
         array_ref._foreign_key.set_(
             ref_model_name="RefSchema",
+            logical_name="logical name 1",
             model_schema=model_schema,
             schemas={},
             fk_column=fk_column,
@@ -57,6 +58,7 @@ def test_schemas(schemas):
 
     array_ref._foreign_key.set_(
         ref_model_name=ref_model_name,
+        logical_name="logical name 1",
         model_schema=model_schema,
         schemas=schemas,
         fk_column=fk_column,
@@ -69,7 +71,7 @@ def test_schemas(schemas):
                 {
                     "type": "object",
                     "properties": {
-                        f"{tablename}_{fk_column}": {
+                        f"{tablename}_logical name 1_{fk_column}": {
                             "type": "integer",
                             "x-foreign-key": f"{tablename}.{fk_column}",
                             "x-dict-ignore": True,
@@ -104,12 +106,13 @@ def test_models(mocked_facades_models: mock.MagicMock):
 
     array_ref._foreign_key.set_(
         ref_model_name=ref_model_name,
+        logical_name="logical name 1",
         model_schema=model_schema,
         schemas=schemas,
         fk_column=fk_column,
     )
 
-    added_fk_column = getattr(mock_ref_model, f"{tablename}_{fk_column}")
+    added_fk_column = getattr(mock_ref_model, f"{tablename}_logical name 1_{fk_column}")
     assert isinstance(added_fk_column.type, facades.sqlalchemy.column.Integer)
     foreign_key = list(added_fk_column.foreign_keys)[0]
     assert f"{tablename}.{fk_column}" in str(foreign_key)
@@ -137,13 +140,17 @@ def test_fk_def():
             "type": "object",
             "x-tablename": "ref_schema",
             "properties": {
-                "schema_id": {"type": "integer", "x-foreign-key": "schema.id"}
+                f"{tablename}_logical name 1_id": {
+                    "type": "integer",
+                    "x-foreign-key": "schema.id",
+                }
             },
         }
     }
 
     array_ref._foreign_key.set_(
         ref_model_name=ref_model_name,
+        logical_name="logical name 1",
         model_schema=model_schema,
         schemas=schemas,
         fk_column=fk_column,
@@ -154,7 +161,10 @@ def test_fk_def():
             "type": "object",
             "x-tablename": "ref_schema",
             "properties": {
-                "schema_id": {"type": "integer", "x-foreign-key": "schema.id"}
+                f"{tablename}_logical name 1_id": {
+                    "type": "integer",
+                    "x-foreign-key": "schema.id",
+                }
             },
         }
     }
diff --git a/tests/open_alchemy/column_factory/array_ref/test_integration.py b/tests/open_alchemy/column_factory/array_ref/test_integration.py
index 920553ee..7d71e45a 100644
--- a/tests/open_alchemy/column_factory/array_ref/test_integration.py
+++ b/tests/open_alchemy/column_factory/array_ref/test_integration.py
@@ -48,7 +48,7 @@ def test_handle_array():
                 {
                     "type": "object",
                     "properties": {
-                        f"{tablename}_id": {
+                        f"{tablename}_ref_schema_id": {
                             "type": "integer",
                             "x-foreign-key": f"{tablename}.id",
                             "x-dict-ignore": True,
@@ -111,7 +111,7 @@ def test_handle_array_backref():
                 {
                     "type": "object",
                     "properties": {
-                        f"{tablename}_id": {
+                        f"{tablename}_ref_schema_id": {
                             "type": "integer",
                             "x-foreign-key": f"{tablename}.id",
                             "x-dict-ignore": True,
diff --git a/tests/open_alchemy/column_factory/array_ref/test_link.py b/tests/open_alchemy/column_factory/array_ref/test_link.py
index 91fd8fe8..cee9e4df 100644
--- a/tests/open_alchemy/column_factory/array_ref/test_link.py
+++ b/tests/open_alchemy/column_factory/array_ref/test_link.py
@@ -20,6 +20,7 @@ def test_schemas():
     ref_schema = {"type": "object", "x-tablename": "ref_schema", "properties": {}}
     artifacts = types.ObjectArtifacts(
         spec=copy.deepcopy(ref_schema),
+        logical_name="ref_schema",
         fk_column="id",
         relationship=types.RelationshipArtifacts(model_name="RefSchema"),
     )
@@ -42,7 +43,7 @@ def test_schemas():
                 {
                     "type": "object",
                     "properties": {
-                        f"{tablename}_id": {
+                        f"{tablename}_ref_schema_id": {
                             "type": "integer",
                             "x-foreign-key": f"{tablename}.id",
                             "x-dict-ignore": True,
@@ -69,6 +70,7 @@ def test_secondary(mocked_facades_models):
     secondary = "association"
     artifacts = types.ObjectArtifacts(
         spec=copy.deepcopy(ref_schema),
+        logical_name="logical name 1",
         fk_column="id",
         relationship=types.RelationshipArtifacts(
             model_name="RefSchema", secondary=secondary
diff --git a/tests/open_alchemy/column_factory/array_ref/test_schema.py b/tests/open_alchemy/column_factory/array_ref/test_schema.py
index a33a1536..82a61ef5 100644
--- a/tests/open_alchemy/column_factory/array_ref/test_schema.py
+++ b/tests/open_alchemy/column_factory/array_ref/test_schema.py
@@ -13,6 +13,7 @@ from open_alchemy.column_factory import array_ref
         (
             types.ObjectArtifacts(
                 spec={},
+                logical_name="logical name 1",
                 fk_column="fk_column",
                 relationship=types.RelationshipArtifacts("RefSchema"),
             ),
@@ -21,6 +22,7 @@ from open_alchemy.column_factory import array_ref
         (
             types.ObjectArtifacts(
                 spec={},
+                logical_name="logical name 1",
                 fk_column="fk_column",
                 relationship=types.RelationshipArtifacts("RefSchema"),
                 description="description 1",
diff --git a/tests/open_alchemy/column_factory/helpers/test_backref.py b/tests/open_alchemy/column_factory/helpers/test_backref.py
index 9e0d5043..cb2cefb4 100644
--- a/tests/open_alchemy/column_factory/helpers/test_backref.py
+++ b/tests/open_alchemy/column_factory/helpers/test_backref.py
@@ -36,6 +36,7 @@ class TestCalculateSchema:
         """
         artifacts = types.ObjectArtifacts(
             spec={},
+            logical_name="logical name 1",
             fk_column="fk_column",
             relationship=types.RelationshipArtifacts(
                 model_name="RefModel", back_reference=None, secondary=None
@@ -89,6 +90,7 @@ class TestCalculateSchema:
         """
         artifacts = types.ObjectArtifacts(
             spec={},
+            logical_name="logical name 1",
             fk_column="fk_column",
             relationship=types.RelationshipArtifacts(
                 model_name="RefModel",
@@ -115,6 +117,7 @@ def test_record_backref_none():
     """
     artifacts = types.ObjectArtifacts(
         spec={},
+        logical_name="logical name 1",
         fk_column="fk_column",
         relationship=types.RelationshipArtifacts(
             model_name="RefModel", back_reference=None, secondary=None
@@ -138,6 +141,7 @@ def test_record():
     """
     artifacts = types.ObjectArtifacts(
         spec={},
+        logical_name="logical name 1",
         fk_column="fk_column",
         relationship=types.RelationshipArtifacts(
             model_name="RefModel",
diff --git a/tests/open_alchemy/column_factory/object_ref/test_artifacts.py b/tests/open_alchemy/column_factory/object_ref/test_artifacts.py
index ba5cc4ed..081461a2 100644
--- a/tests/open_alchemy/column_factory/object_ref/test_artifacts.py
+++ b/tests/open_alchemy/column_factory/object_ref/test_artifacts.py
@@ -148,6 +148,23 @@ def test_gather_object_artifacts_spec(schema, schemas):
     assert obj_artifacts.spec == {"type": "object"}
 
 
+@pytest.mark.column
+def test_gather_object_artifacts_logical_name():
+    """
+    GIVEN logical name
+    WHEN gather_object_artifacts is called with the logical name
+    THEN the expected logical name is returned.
+    """
+    schema = {"$ref": "#/components/schemas/RefSchema"}
+    schemas = {"RefSchema": {"type": "object"}}
+
+    obj_artifacts = artifacts.gather(
+        schema=schema, logical_name="logical name 1", schemas=schemas
+    )
+
+    assert obj_artifacts.logical_name == "logical name 1"
+
+
 @pytest.mark.parametrize(
     "schema, schemas",
     [
diff --git a/tests/open_alchemy/column_factory/object_ref/test_foreign_key.py b/tests/open_alchemy/column_factory/object_ref/test_foreign_key.py
index 27da357a..41013b4a 100644
--- a/tests/open_alchemy/column_factory/object_ref/test_foreign_key.py
+++ b/tests/open_alchemy/column_factory/object_ref/test_foreign_key.py
@@ -191,7 +191,10 @@ def test_gather_artifacts_malformed_schema(schema, schemas, fk_column):
     """
     with pytest.raises(exceptions.MalformedSchemaError):
         foreign_key.gather_artifacts(
-            model_schema=schema, schemas=schemas, fk_column=fk_column
+            model_schema=schema,
+            logical_name="logical name 1",
+            schemas=schemas,
+            fk_column=fk_column,
         )
 
 
@@ -304,11 +307,12 @@ def test_gather_artifacts_return(
 
     logical_name, artifacts = foreign_key.gather_artifacts(
         model_schema=schema,
+        logical_name="logical name 1",
         schemas=schemas,
         fk_column="fk",
         required=required,
         nullable=nullable,
     )
 
-    assert logical_name == "table 1_fk"
+    assert logical_name == "logical name 1_fk"
     assert artifacts == expected_artifacts
diff --git a/tests/open_alchemy/column_factory/object_ref/test_schema.py b/tests/open_alchemy/column_factory/object_ref/test_schema.py
index 32b864d0..af927c40 100644
--- a/tests/open_alchemy/column_factory/object_ref/test_schema.py
+++ b/tests/open_alchemy/column_factory/object_ref/test_schema.py
@@ -13,6 +13,7 @@ from open_alchemy.column_factory import object_ref
         (
             types.ObjectArtifacts(
                 spec={},
+                logical_name="logical name 1",
                 fk_column="fk_column",
                 relationship=types.RelationshipArtifacts("RefSchema"),
             ),
@@ -21,6 +22,7 @@ from open_alchemy.column_factory import object_ref
         (
             types.ObjectArtifacts(
                 spec={},
+                logical_name="logical name 1",
                 fk_column="fk_column",
                 relationship=types.RelationshipArtifacts("RefSchema"),
                 nullable=True,
@@ -30,6 +32,7 @@ from open_alchemy.column_factory import object_ref
         (
             types.ObjectArtifacts(
                 spec={},
+                logical_name="logical name 1",
                 fk_column="fk_column",
                 relationship=types.RelationshipArtifacts("RefSchema"),
                 nullable=False,
@@ -39,6 +42,7 @@ from open_alchemy.column_factory import object_ref
         (
             types.ObjectArtifacts(
                 spec={},
+                logical_name="logical name 1",
                 fk_column="fk_column",
                 relationship=types.RelationshipArtifacts("RefSchema"),
                 description="description 1",
diff --git a/tests/open_alchemy/column_factory/test_integration.py b/tests/open_alchemy/column_factory/test_integration.py
index a65a76ee..17652c4e 100644
--- a/tests/open_alchemy/column_factory/test_integration.py
+++ b/tests/open_alchemy/column_factory/test_integration.py
@@ -274,7 +274,7 @@ def test_integration_array_ref():
                 {
                     "type": "object",
                     "properties": {
-                        "schema_id": {
+                        "schema_ref_schema_id": {
                             "type": "integer",
                             "x-foreign-key": "schema.id",
                             "x-dict-ignore": True,
diff --git a/tests/open_alchemy/integration/test_database/test_relationship.py b/tests/open_alchemy/integration/test_database/test_relationship.py
index c39fbef7..4929ff02 100644
--- a/tests/open_alchemy/integration/test_database/test_relationship.py
+++ b/tests/open_alchemy/integration/test_database/test_relationship.py
@@ -240,7 +240,7 @@ def test_one_to_many(engine, sessionmaker):
     assert len(queried_model.ref_tables) == 1
     assert queried_model.ref_tables[0].id == 11
     assert queried_model.ref_tables[0].name == "ref table name 1"
-    assert queried_model.ref_tables[0].table_id == 12
+    assert queried_model.ref_tables[0].table_ref_tables_id == 12
     assert queried_model.ref_tables[0].table.name == "table name 1"
     queried_ref_model = session.query(ref_model).first()
     assert queried_ref_model.id == 11
@@ -535,3 +535,89 @@ def test_ref_all_of(engine, sessionmaker, spec):
     # Querying session
     queried_model = session.query(model).first()
     assert queried_model.column == 1
+
+
+@pytest.mark.integration
+def test_multiple(engine, sessionmaker):
+    """
+    GIVEN specification with a schema with multiple relationships pointing to the same
+        table
+    WHEN schema is created, values inserted in both tables and queried
+    THEN the data is returned as it was inserted with the correct foreign key.
+    """
+    # Defining specification
+    spec = {
+        "components": {
+            "schemas": {
+                "RefTable": {
+                    "properties": {
+                        "id": {"type": "integer", "x-primary-key": True},
+                        "name": {"type": "string"},
+                    },
+                    "x-tablename": "ref_table",
+                    "type": "object",
+                },
+                "Table": {
+                    "properties": {
+                        "id": {"type": "integer", "x-primary-key": True},
+                        "name": {"type": "string"},
+                        "ref_table_first": {
+                            "allOf": [
+                                {"$ref": "#/components/schemas/RefTable"},
+                                {
+                                    "x-kwargs": {
+                                        "foreign_keys": "Table.ref_table_first_id"
+                                    }
+                                },
+                            ]
+                        },
+                        "ref_table_second": {
+                            "allOf": [
+                                {"$ref": "#/components/schemas/RefTable"},
+                                {
+                                    "x-kwargs": {
+                                        "foreign_keys": "Table.ref_table_second_id"
+                                    }
+                                },
+                            ]
+                        },
+                    },
+                    "x-tablename": "table",
+                    "type": "object",
+                },
+            }
+        }
+    }
+    # Creating model factory
+    base = declarative.declarative_base()
+    model_factory = open_alchemy.init_model_factory(spec=spec, base=base)
+    model = model_factory(name="Table")
+    ref_model = model_factory(name="RefTable")
+
+    # Creating models
+    base.metadata.create_all(engine)
+    # Creating instance of model and ref_model
+    ref_model_instance_first = ref_model(id=11, name="ref table name 1")
+    ref_model_instance_second = ref_model(id=21, name="ref table name 2")
+    model_instance = model(
+        id=12,
+        name="table name 1",
+        ref_table_first=ref_model_instance_first,
+        ref_table_second=ref_model_instance_second,
+    )
+    session = sessionmaker()
+    session.add(ref_model_instance_first)
+    session.add(ref_model_instance_second)
+    session.add(model_instance)
+    session.flush()
+
+    # Querying session
+    queried_model = session.query(model).first()
+    assert queried_model.id == 12
+    assert queried_model.name == "table name 1"
+    assert queried_model.ref_table_first_id == 11
+    assert queried_model.ref_table_first.id == 11
+    assert queried_model.ref_table_second_id == 21
+    assert queried_model.ref_table_second.id == 21
+    assert queried_model.ref_table_first.name == "ref table name 1"
+    assert queried_model.ref_table_second.name == "ref table name 2"
diff --git a/tests/open_alchemy/integration/test_to_from_dict.py b/tests/open_alchemy/integration/test_to_from_dict.py
index 29a4240e..2b157a1d 100644
--- a/tests/open_alchemy/integration/test_to_from_dict.py
+++ b/tests/open_alchemy/integration/test_to_from_dict.py
@@ -294,7 +294,7 @@ def test_to_from_dict_one_to_many_fk_def(engine, sessionmaker):
                     "RefTable": {
                         "properties": {
                             "id": {"type": "integer", "x-primary-key": True},
-                            "table_id": {
+                            "table_ref_tables_id": {
                                 "type": "integer",
                                 "x-foreign-key": "table.id",
                             },
@@ -329,7 +329,7 @@ def test_to_from_dict_one_to_many_fk_def(engine, sessionmaker):
     session.add(instance)
     session.flush()
     queried_ref_instance = session.query(ref_model).first()
-    assert queried_ref_instance.to_dict() == {"id": 12, "table_id": 11}
+    assert queried_ref_instance.to_dict() == {"id": 12, "table_ref_tables_id": 11}
 
 
 @pytest.mark.integration