volatiletech / sqlboiler

Generate a Go ORM tailored to your database schema.
BSD 3-Clause "New" or "Revised" License
6.73k stars 544 forks source link

How to use many to many models for insert #209

Closed AlbinOS closed 7 years ago

AlbinOS commented 7 years ago

Hello everyone !

First I'd like to thanks everybody for this awesome project !

I'm wondering on how to insert properly using a many to many relationship with sqlboiler.

Here is my simplified schema:

CREATE TABLE scene (
  id bigserial PRIMARY KEY
);

CREATE TABLE sensor (
  id bigserial PRIMARY KEY
);

CREATE TABLE sensor_scene (
  sensor_id BIGINT NOT NULL REFERENCES sensor (id) ON UPDATE CASCADE ON DELETE CASCADE,
  scene_id BIGINT NOT NULL REFERENCES scene (id) ON UPDATE CASCADE ON DELETE CASCADE,
  PRIMARY KEY (sensor_id, scene_id)
);

What I was expecting was something like:

var sensor1 models.Sensor
var scene1 models.Scene
sensor1.SetScene(&scene1) or scene1.SetSensor(&sensor1)

But What I'm doing right now is:

var sensor1 models.Sensor
sensor1.InsertG()

var scene1 models.Scene
scene1.InsertG()

var ss1 models.SensorScene
ss1.SetSceneG(false, scene1)
ss1.SetSensorG(false, &sensor1)
ss1.InsertG()

Am I missing something ?

Thanks a lot and kind regards, Albin.

AlbinOS commented 7 years ago

Other aspect is the eager loading, I don't really understand how to make it work:

response, err := models.ScenesG(
    qm.Where("id = ?", 1),
    qm.Load("Sensors")).One()
ERRO[0000] models: failed to execute a one query for scene: could not find LoadSensors method for eager loading

What am I doing wrong ?

Thanks a lot !

aarondl commented 7 years ago

Sorry for the late reply. I was in Europe on business for quite a few days. Unfortunately for you first answer, there is no magic syntax that we have that will make that less painful to do. Having said that I don't think it's THAT bad, and it's about as efficient as you can get in terms of actual calls out to the database too. One important thing about it is that because it mirrors the calls to the database directly you will always know where the calls out to the database and therefore the slowness is happening. So you're doing the first part right.

The second part is likely that the relationship is such that you have a scene, which has a sensor. So instead of qm.Load("Sensors") you actually have to type qm.Load("Sensor"). It's sort of an implementation detail that stinks but it's necessary because it's possible you have both relationships to the same model and therefore you'd have to distinguish in some way, and the only way would be that name :(

Also the mailing list is a good place for questions like these, as well as Slack. Try to open issues for bugs only, thanks!

AlbinOS commented 7 years ago

Hi @aarondl and thanks a lot for the complete reply !

I'll join the slack next time then, thanks a lot :-).