Comments (7)
Hi @btxtiger, using the query builder you do not need to write the name of the column like it's in the database, you can put it as it's declared in your class.
For example, if your User class has a property ofUser (I'm supposing how it's your implementation):
class User {
@PrimaryGeneratedColumn()
id: number
@OneToOne(() => User)
@JoinColumn()
ofUser: User
}
typeorm generates an of_user_id
FK (if your PR is userId
, it would be more verbose, of_user_user_id
), but in any case, you should not worry about the column name in your db, because you can use the property name to do the query instead of the column name generated 🔥:
const user = await userRepository.createQueryBuilder('user')
.where('user.ofUser = :userId', {userId: 1}).getOne();
I think that's your problem, if I'm misunderstanding you, I'm sorry! 😆
from typeorm-naming-strategies.
using the query builder you do not need to write the name of the column like it's in the database, you can put it as it's declared in your class.
Indeed, there was another mistake which prevented it from working. Thanks for explanation!
typeorm generates an of_user_id FK (if your PR is userId, it would be more verbose, of_user_user_id), but in any case, you should not worry about the column name in your db, because you can use the property name to do the query instead of the column name generated
Thats correct, but if you need to use .getRawMany
and .getRawOne
because of using for example subselects with generated columns, you would get a diverging name as property for foreign key columns. It also deprives a bit the control of the programmer, because just using an ORM does not always mean "I don't want do handle the database by myself", especially when using a custom naming strategy. Otherwise i could just use the default settings.
Currently I wrote a cleanup method to get usable data from the .getRaw
methods.
E.g. message_last_modified
-> lastModified
, as it would be without naming strategy.
It just camelCases all properties and optionally removes any table prefixes. If you might find that useful for adding to the snake naming strategy class, I could open a pull request for that.
public static cleanupGetRaw(rawData: RawDataObject | Array<RawDataObject>, deletePrefixes: Array<string> = []): any
from typeorm-naming-strategies.
I think it's interesting, however I have not that problem. How would its use? Can you show me an example?
const data = SnakeNamingStrategy.cleanupGetRaw(await db.builder(...).getRaw()); // Is it?
from typeorm-naming-strategies.
Actually thats all:
let data = await getRepository(User).(...).getRawMany();
/*
{
user_id: 12,
user_full_name: "Peter Shaw",
userProfile_picture_url: "http:// ...."
}
*/
data = SnakeNamingStrategy.cleanupGetRaw(data, ['user', 'userProfile']);
/*
id: 12,
fullName: "Peter",
pictureUrl: "http://"
*/
import { camelCase, snakeCase } from 'typeorm/util/StringUtils';
interface RawData {
[key: string]: any;
}
/**
* Cleanup response objects from .getRawMany and .getRawOne
* @param rawData
* @param deletePrefixes
*/
public static cleanupGetRaw(rawData: RawData | Array<RawData>, deletePrefixes: Array<string> = []): any {
let newName: string, prefixStr: string;
const cleanupRow = (row: RawData) => {
for (const prop in row) {
if (row.hasOwnProperty(prop)) {
newName = prop;
deletePrefixes.map(prefix => {
prefixStr = prefix + '_';
if (newName.startsWith(prefixStr)) {
newName = newName.replace(prefixStr, '');
}
});
newName = camelCase(newName);
this.renameObjectProperty(row, prop, newName);
}
}
};
// Support array or single object
if (rawData instanceof Array) {
for (const row of rawData) {
cleanupRow(row);
}
} else {
cleanupRow(rawData);
}
return rawData;
}
/**
* Rename property in object
* https://stackoverflow.com/questions/4647817/javascript-object-rename-key
* @param obj
* @param oldKey
* @param newKey
*/
public static renameObjectProperty(obj: any, oldKey: string, newKey: string): any {
if (oldKey !== newKey) {
Object.defineProperty(obj, newKey, Object.getOwnPropertyDescriptor(obj, oldKey));
delete obj[oldKey];
}
}
from typeorm-naming-strategies.
I'm running again into that naming issue. Can't it be possible that there is really one?
getRepository(PublicChannelMessage)
.createQueryBuilder('message')
.select()
.addSelect(qb => {
return qb
.select('SUM(vote1.weight)', 'total')
.from('public_channel_message_vote', 'vote1')
.leftJoin('public_channel_message', 'message1', 'vote1.ofMessage = message1.publicChannelMessageId')
.where('vote1.ofMessage = message.publicChannelMessageId');
}, 'totalWeight')
.where('message.ofChannel = :id', { id: channelId })
.getRawMany()
The issue occurres for subqueries. When I'm writing the camelCase name, the query will fail. Outside the subquery it works as usual.
.from('publicChannelMessageVote'
.leftJoin('publicChannelMessage'
code: 'ER_NO_SUCH_TABLE',
errno: 1146,
sqlMessage:
'Table \'chat_orm.publicchannelmessagevote\' doesn\'t exist',
sqlState: '42S02',
index: 0,
from typeorm-naming-strategies.
Hi @btxtiger, I'm trying to replicate your error but I can't. I'm using a subquery as you and it's working like it's expected 😕
from typeorm-naming-strategies.
Anyway, If it's failing It's an error of typeorm, because the expected behavior is that translate the camelCase name to snake_case. Are you sure that your table is registered or that's the correct name?
from typeorm-naming-strategies.
Related Issues (16)
- How to avoid naming change ? HOT 1
- MongoDB integration HOT 2
- Potential Duplicate Package Name HOT 2
- TypeORM module resolution issue after 0.2.42 HOT 2
- problem with StringUtils HOT 6
- Error when using a ncc build with "typeorm-naming-strategies" HOT 1
- Typeorm v0.3.3 support HOT 1
- Using `JoinTable` with `name` causes SQLITE_ERROR
- Duplicate underscore in oneToMany HOT 2
- I am getting this issue on npm run start
- Alias replacement not taking account multiple lines
- Naming strategy doesn't applied to query builder return value HOT 1
- Naming Strategy and Migration Files HOT 7
- Is this project maintained? HOT 1
- TypeError: namingStrategy.tableName is not a function HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from typeorm-naming-strategies.