I am having an issue with OneToMany and ManyToOne.
The error I receive is:
[Nest] 818 - 10/05/2022, 11:41:22 AM
[ExceptionsHandler] Cannot read properties of undefined (reading 'joinColumns')
TypeError: Cannot read properties of undefined (reading 'joinColumns')
Here is the many side - variant:
#ManyToOne(() => EDC_PRODUCT, (prod) => prod.variants)
#JoinColumn({ name: 'edcProdId' })
edcProd: EDC_PRODUCT;
Here is the one side - product
#OneToMany(
() => EDC_VARIANT,
(variant) => {
variant.edcProd;
},
)
#JoinColumn({ referencedColumnName: 'edcProdId' })
variants: EDC_VARIANT[];
I have tried using JoinColumn decorator and omitting it. Both have the same error.
When I save product object the variants attribute is populated.
variants: EDC_VARIANT {
id: 121294,
type: 'S',
subArtNr: '1001-BLU-S',
ean: '8683702000855',
createdDate: 2022-10-04T20:21:40.622Z,
updatedDate: 2022-10-04T20:21:40.622Z,
version: 1
}
Any assistance would be appreciated.
Revised the definitions
Product
#OneToMany((_type) => EDC_VARIANT, (variant) => variant.edcProd)
variants: EDC_VARIANT[];
Variant side
#ManyToOne(() => EDC_PRODUCT, (prod: EDC_PRODUCT) => prod.variants)
edcProd: EDC_PRODUCT;
Related
I was following this article TypeORM Best Practices using Typescript and NestJS at Libeo.
I got to the point of using nominal typing in our entity ID
#PrimaryGeneratedColumn("uuid")
id!: string & { __brand: "userId" };
but cannot use it in find operation example
async getUserById(id: User['id']) {
const user = await this.findOne({
where: { id: 'id' },
});
return user;
},
I am having the following errors
Type '{ id: string; }' is not assignable to type 'FindOptionsWhere<User> | FindOptionsWhere<User>[] | undefined'.
Types of property 'id' are incompatible.
Type 'string' is not assignable to type 'boolean | FindOperator<any> | never[] | EqualOperator<never> | undefined'.
where: { id: 'id' },
Actually don't know what am doing wrong.
but if I remove the nominal part everything works very well
#PrimaryGeneratedColumn("uuid")
id!: string
I have also tried using just Primary Column
#PrimaryColumn("uuid")
id!: string & { __brand: "userId" };
Still not working. I think it has to do with the FindOption
enum UserIdBrand {
__type = 'User',
}
type UserId = string & UserIdBrand;
#hittingonme Thanks
Also using enum didn't work, had to declare it as a type UserId
category.ts
#Entity('categoryenter code here')
export class Category{
#PrimaryGeneratedColumn({ type: 'int' })
id: Category;
#OneToMany(() => Category, category => category.category,{eager:true})
categoryList: Category[];
#ManyToOne(() => Category, (category) => category.categoryList)
category: Category;
}
The Category entity is above(mysql).
I want to find a category with all it's children like this
await categoryRepo.findOne({
where:{ id: 1 },
relations:['categoryList']
})
But I got an error Maximum call stack size exceeded
What am I suppose to do
Actually, as I see, you are trying to make a tree data structure. TypeORM has some decorators for that. Here is an example:
import {
Entity, BaseEntity, Column,
PrimaryGeneratedColumn, Tree,
TreeParent, TreeChildren
} from 'typeorm';
#Tree('materialized-path')
#Entity({ name: 'Menu' })
export class Category extends BaseEntity {
#PrimaryGeneratedColumn({ type: 'int' })
id: number;
#Column({ type: 'varchar', length: 50 })
text: string;
// Check bellow
#TreeParent()
parent: Category;
#TreeChildren()
children: Category[];
}
The decorator #Tree() is used to tell to TypeORM that every Instance has self references for itself. Every item should have one parent, and should have several children. The ancestors and descendant can be setted with the decorators #TreeParent() and #TreeChildren() respectively. Check the documentation for more details about the different modes available for #Tree() decorator.
Since you have eager loading, each Category object is trying to load all its children eligible for categoryList. And since categoryList is also a list of Category entities, all it's children are also trying to load categoryList of their own. And this goes on and on until the stack is overflowed.
Remove eager loading from Category entity:
#Entity('categoryenter code here')
export class Category{
#PrimaryGeneratedColumn({ type: 'int' })
id: Category;
#OneToMany(() => Category, category => category.category)
categoryList: Category[];
#ManyToOne(() => Category, (category) => category.categoryList)
category: Category;
}
I've got this entity class:
#Entity("organization")
export class OrganizationEntity {
// ...
#PrimaryColumn({name: "party_id"})
#OneToOne(() => PartyEntity, {cascade: true})
#JoinColumn({name: "party_id", referencedColumnName: "id"})
party: PartyEntity
}
Then I create a new OrganizationEntity and persist it:
const savedOrganizationEntity = await this.organizationTypeOrmRepository.save(organizationEntity);
// see Repository.save
However, the returned savedOrganizationEntity contains a string in the field party, not a PartyEntity object.
How can I fix this behaviour, so that OrganizationEntity.party contains a PartyEntity, not a string?
The behaviour is working as designed: https://github.com/typeorm/typeorm/issues/3490
Trying to import excel data to my mysql db and getting ErrorException Undefined offset: 0.
Tried using var_dump($row) to check the array of the row of the data. It looks off and not sure how to make the data shows nicely so that able to pass to db.
array(5) { ["a"]=> string(1) "B" ["white"]=> string(5) "Green" ["example1_at_gmailcom"]=> string(18) "example2#gmail.com" [60123456789]=> int(60162313142) [5]=> int(5) }
This is my excel data:
Model
public function model(array $row)
{
var_dump($row);
return new ContactList([
'first_name' => $row[0],
'last_name' => $row[1],
'email' => $row[2],
'phone' => $row[3],
'group_id' => $row[4],
]);
}
I already tried using replacing the $row[] with string and it works perfectly storing the data into my db.
Controller
if($request->hasFile('selected_file')){
$file = $request->file('selected_file');
Excel::import(new ContactListsImport, $file);
return redirect()->back()->with('success', 'Data saved successfully!');
}
You need to remove the WithHeadingRow interface from your Import class to use numeric indexes for the array.
As per the documentation, when your Import class implements WithHeadingRow it will use the first row for the indexes of the array and in turn remove it from the rows that are provided.
I did some searching around but didnt seem to find an answer. I'm new to Angular, for this project im working on an webstore, i did use a tutorial but came across an error.
import { select, Store } from '#ngrx/store';
import { GetItems } from '../store/actions';
import { Product } from '../product/product.component';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
constructor(private store: Store<{ items: Product[]; cart: [] }>) {
store.pipe(select('shop')).subscribe(data => (this.items = data.items));
}
items: Product[] = [];
ngOnInit() {
this.store.dispatch(new GetItems());
}
}
the error im getting is:
src/app/home/home.component.ts:13:25 - error TS2769: No overload matches this call.
Overload 1 of 8, '(mapFn: (state: { items: Product[]; cart: []; }, props: unknown) => unknown, props?: unknown): (source$: Observable<{ items: Product[]; cart: []; }>) => Observable', gave the following error.
Argument of type '"shop"' is not assignable to parameter of type '(state: { items: Product[]; cart: []; }, props: unknown) => unknown'.
Overload 2 of 8, '(key: "items" | "cart"): (source$: Observable<{ items: Product[]; cart: []; }>) => Observable<[] | Product[]>', gave the following error.
Argument of type '"shop"' is not assignable to parameter of type '"items" | "cart"'.
13 store.pipe(select('shop')).subscribe(data => (this.items = data.items));
~~~~~~
src/app/home/home.component.ts:13:71 - error TS2339: Property 'items' does not exist on type 'unknown'.
13 store.pipe(select('shop')).subscribe(data => (this.items = data.items));
I can't seem to find the problem. Even starting the app is giving me difficulties. Sometimes it starts in one go, sometimes i need to try it 5 times. But the weird thing is, the moment it starts, everything works as inteded, but with errors in my CMD.
I feel like there's something wrong with my ngrx/store.
You need to do the following things to get more specific error -
1) Create an interface (AppState) and pass it while you initiating the Store, which would be the initial state -
private store: Store<AppState>
2) Create an Selector/FeatureSelector to select any part of the state.
You can find the more detail here - https://ngrx.io/guide/store/selectors