[英]How to get column name for primary_key at database level?
I need to get the column name containing the primary key(s) at the database level. 我需要在数据库级别获取包含主键的列名。
Model.primary_key
returns models_id
column name which is not the primary key at the database level. Model.primary_key
返回的models_id
列名称不是数据库级别的主键。 I cannot change migrations or modify the tables in anyway. 无论如何,我无法更改迁移或修改表。
I can currently get it through the MySqlAdapter with ActiveRecord::Base.connection.primary_key('table_name')
我目前可以通过MySqlAdapter使用
ActiveRecord::Base.connection.primary_key('table_name')
来获取它
but this does not work with tables that have composite primary keys. 但这不适用于具有复合主键的表。 If the table contains a composite primary key it returns
nil
. 如果表包含复合主键,则返回
nil
。
Is there any way I can achieve this programatically? 有什么办法可以通过编程实现这一目标吗?
ActiveRecord does not support composite primary keys out of the box. ActiveRecord不支持开箱即用的复合主键。
You'll need to install the composite_primary_keys gem and then ActiveRecord::Base.connection.primary_key('table_name')
will return an array of column names if the primary key is composite. 您需要安装Composite_primary_keys gem ,然后,如果主键是复合键,则
ActiveRecord::Base.connection.primary_key('table_name')
将返回一个列名数组。
Execute the query: 执行查询:
SHOW COLUMNS FROM table_name;
Then look at all the rows returned where the columns named KEY has the value 'PRI' . 然后查看返回的所有行,其中名为KEY的列的值为'PRI' 。 Then column Field will give you the column name in your table that forms part of the table's primary key.
然后, Field列将为您提供表中构成表主键一部分的列名。
Alternatively: 或者:
SELECT COLUMN_NAME FROM information_schema WHERE TABLE_SCHEMA='database_name' AND TABLE_NAME = 'table_name' AND COLUMN_KEY = 'PRI';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.