car.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "time"
  7. "code.osinet.fr/fgm/go__ent_demo/ent"
  8. "code.osinet.fr/fgm/go__ent_demo/ent/car"
  9. )
  10. func CreateCars(ctx context.Context, client *ent.Client) (*ent.User, error) {
  11. var model string
  12. model = "Tesla"
  13. tesla, err := client.Car.
  14. Create().
  15. SetModel(model).
  16. SetRegisteredAt(time.Now()).
  17. Save(ctx)
  18. if err != nil {
  19. return nil, fmt.Errorf("failed creating %s car: %w", model, err)
  20. }
  21. log.Println("car was created: ", tesla)
  22. model = "Ford"
  23. ford, err := client.Car.
  24. Create().
  25. SetModel(model).
  26. SetRegisteredAt(time.Now()).
  27. Save(ctx)
  28. if err != nil {
  29. return nil, fmt.Errorf("failed creating %s car: %w", model, err)
  30. }
  31. log.Println("car was created: ", ford)
  32. a8m, err := client.User.
  33. Create().
  34. SetAge(30).
  35. SetName(name).
  36. AddCars(tesla, ford).
  37. Save(ctx)
  38. if err != nil {
  39. return nil, fmt.Errorf("failed creating user: %w", err)
  40. }
  41. log.Println("User created ", a8m)
  42. return a8m, nil
  43. }
  44. func QueryCars(ctx context.Context, a8m *ent.User) error {
  45. cars, err := a8m.QueryCars().All(ctx)
  46. if err != nil {
  47. return fmt.Errorf("querying %s's cars: %w", a8m.Name, err)
  48. }
  49. log.Println("returned cars: ", cars)
  50. // What about specific cars
  51. ford, err := a8m.QueryCars().
  52. Where(car.Model("Ford")).
  53. Only(ctx)
  54. if err != nil {
  55. return fmt.Errorf("querying %s's Ford: %w", a8m.Name, err)
  56. }
  57. log.Println("returned ford: ", ford)
  58. return nil
  59. }