12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- package main
- import (
- "context"
- "fmt"
- "log"
- "time"
- "code.osinet.fr/fgm/go__ent_demo/ent"
- "code.osinet.fr/fgm/go__ent_demo/ent/car"
- )
- func CreateCars(ctx context.Context, client *ent.Client) (*ent.User, error) {
- var model string
- model = "Tesla"
- tesla, err := client.Car.
- Create().
- SetModel(model).
- SetRegisteredAt(time.Now()).
- Save(ctx)
- if err != nil {
- return nil, fmt.Errorf("failed creating %s car: %w", model, err)
- }
- log.Println("car was created: ", tesla)
- model = "Ford"
- ford, err := client.Car.
- Create().
- SetModel(model).
- SetRegisteredAt(time.Now()).
- Save(ctx)
- if err != nil {
- return nil, fmt.Errorf("failed creating %s car: %w", model, err)
- }
- log.Println("car was created: ", ford)
- a8m, err := client.User.
- Create().
- SetAge(30).
- SetName(name).
- AddCars(tesla, ford).
- Save(ctx)
- if err != nil {
- return nil, fmt.Errorf("failed creating user: %w", err)
- }
- log.Println("User created ", a8m)
- return a8m, nil
- }
- func QueryCars(ctx context.Context, a8m *ent.User) error {
- cars, err := a8m.QueryCars().All(ctx)
- if err != nil {
- return fmt.Errorf("querying %s's cars: %w", a8m.Name, err)
- }
- log.Println("returned cars: ", cars)
- // What about specific cars
- ford, err := a8m.QueryCars().
- Where(car.Model("Ford")).
- Only(ctx)
- if err != nil {
- return fmt.Errorf("querying %s's Ford: %w", a8m.Name, err)
- }
- log.Println("returned ford: ", ford)
- return nil
- }
|