question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Not loading data from @OneToOne relation

See original GitHub issue

There is a problem with loading object from database. The creating and saving works (I looked in the database) but when loading from database it doesn’t load the data from relation.

import "reflect-metadata";

import { createConnection } from "typeorm";

import { Post } from "./post";
import { PostDetails } from "./post-details";

async function main() {
    try {
        console.log(`Before connection!`);
        let connection = await createConnection({
            driver: {
                type: "mysql",
                host: "localhost",
                port: 3306,
                username: "root",
                password: "qwerty123",
                database: "typeorm"
            },
            entities: [
                Post, PostDetails
            ],
            logging: {
                logQueries: true,
                logFailedQueryError: true,
            },
            autoSchemaSync: true,
        });
        console.log(`Connected!`);

        let post = new Post();
        post.title = "Title";
        post.text = "Lorem ipsum";
        post.details = new PostDetails();
        post.details.testField = "test";
        console.log(post);
        post = await connection.getRepository(Post).persist(post);
        console.log(post);
        let loadedPost = await connection.getRepository(Post).findOneById(post.id);
        console.log(loadedPost);

        console.log(`Saved ok!`);
        process.exit(0);
    } catch (error) {
        console.log(`Error!`, error);
        process.exit(1);
    }
}

main();

My entities:

import { Table, PrimaryGeneratedColumn, Column, OneToOne, JoinColumn } from "typeorm";
import { PostDetails } from "./post-details";

@Table()
export class Post {
    @PrimaryGeneratedColumn()
    public id: number;

    @Column()
    title: string;

    @Column("text")
    text: string;

    @JoinColumn()
    @OneToOne(type => PostDetails, { cascadeInsert: true, nullable: true })
    details: PostDetails | null;
}
import { Table, PrimaryGeneratedColumn, Column } from "typeorm";

@Table()
export class PostDetails {
    @PrimaryGeneratedColumn()
    public id: number;

    @Column()
    testField: string;
}

Created object looks like this:

Post {
  title: 'Title',
  text: 'Lorem ipsum',
  details: PostDetails { testField: 'test', id: 1 },
  id: 1 }

But it generates sql without joins on relation, so only id is returned not the data: SELECT post.id AS post_id, post.title AS post_title, post.text AS post_text, post.details AS post_details FROM post post WHERE post.id=? -- PARAMETERS: [1] So the loaded object has empty details field:

Post { id: 1, title: 'Title', text: 'Lorem ipsum' }

This is a bug or I should add some decorator in PostDetails?

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:19 (15 by maintainers)

github_iconTop GitHub Comments

10reactions
pleerockcommented, Jun 30, 2017
        let loadedPost = await connection.getRepository(Post).findOneById(post.id);

findOneById never joins relations by itself, you need to specify manually what relations you want to join. This is implemented this way because your object can have tons of relations, which can be nested deep and even recursive, thats why its not possible to always join all relations. User needs to be explicit what he wants. You have two choices: use query builder or provide find options to findOneById method. Docs for both you can find on site

9reactions
MichalLytekcommented, Sep 29, 2016

findOneById never joins relations by itself, you need to specify manually what relations you want to join. This is implemented this way because your object can have tons of relations, which can be nested deep and even recursive, thats why its not possible to always join all relations.

It’s not an user friendly solution. People use ORM to simplify data access - just use @Decorator and don’t worry about foreing keys, joins and other stuffs.

If someone have relation which might be bigger (not one-to-one) eg. 1000 relations, and he don’t want do load it all, he can use lazy relations. But when I add new relation to my class I have to remember to change joins in all query builder or make another layer with custom repository which will do that.

I think we should stick to the idea of Hibernate - eager and lazy loding. QueryBuilder or joins in find should be used only to make custom joins on columns that aren’t defined as relations.

Read more comments on GitHub >

github_iconTop Results From Across the Web

One to one relationship doesn't work - Stack Overflow
It would mean you make a request for each post. As you can see Hibernate generated 4 queries for you with one of...
Read more >
One-to-one relationships - Django documentation
To define a one-to-one relationship, use OneToOneField . In this example, a Place optionally can be a Restaurant : from django.db import models...
Read more >
One-to-one relations - typeorm - GitBook
One-to-one is a relation where A contains only one instance of B, and B contains only one instance of A. Let's take for...
Read more >
One-to-One relationship not working - Power Pivot - MSDN
Easiest solution is probably to do a merge join in Power Query (maybe a left join looking at your data) so that that...
Read more >
Configuring One To One Relationships In Entity Framework ...
If it is unable to do this, either because the foreign key property name does not follow convention, or because it has not...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found