LoginSignup
0
0

More than 3 years have passed since last update.

SQLBoilerでhas both field and method named IDエラーになる場合の対処法

Posted at

SQLBoilerの使い方

has both field and method named IDのエラーが出る場合、
あるテーブル同士のリレーションがhasOneになっているケースです。

                            Table "public.spans"
     Column     |           Type           | Collation | Nullable | Default 
----------------+--------------------------+-----------+----------+---------
 id             | character varying(40)    |           | not null | 
 highlight_text | text                     |           | not null | 
 category_id    | character varying(40)    |           | not null | 
 page_num       | integer                  |           | not null | 
 corrdinate     | character varying(255)   |           |          | 
 created_at     | timestamp with time zone |           | not null | now()
Indexes:
    "spans_pkey" PRIMARY KEY, btree (id)
    "idx_spans_category_id" btree (category_id)
Foreign-key constraints:
    "spans_annotation_id_fkey" FOREIGN KEY (id) REFERENCES annotations(id)
    "spans_category_id_fkey" FOREIGN KEY (category_id) REFERENCES categories(id)

これはspansというテーブルがannotationsのIDをprimary keyとして参照しています。
これだと、sqlboilerで生成した、モデルがIDがfieldとmethodがかぶってしまうというケースが起こります。
これはこれで修正されれば良いですが、対処法としては、

spansテーブルのidannotation_idというように、参照しているテーブルの名前に変更してやるのが一番簡単な解決策となります。

よって

                            Table "public.spans"
     Column     |           Type           | Collation | Nullable | Default 
----------------+--------------------------+-----------+----------+---------
 annotation_id  | character varying(40)    |           | not null | 
 highlight_text | text                     |           | not null | 
 category_id    | character varying(40)    |           | not null | 
 page_num       | integer                  |           | not null | 
 corrdinate     | character varying(255)   |           |          | 
 created_at     | timestamp with time zone |           | not null | now()
Indexes:
    "spans_pkey" PRIMARY KEY, btree (annotation_id)
    "idx_spans_category_id" btree (category_id)
Foreign-key constraints:
    "spans_annotation_id_fkey" FOREIGN KEY (annotation_id) REFERENCES annotations(id)
    "spans_category_id_fkey" FOREIGN KEY (category_id) REFERENCES categories(id)

このようなidだったprimary keyがannotation_idという名前に変更したテーブル設計になればエラーも起こらなくなります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0