Inserting rows in tables that don't have 'id' column

Inserting rows in tables that don't have 'id' column

by Julen Pardo -
Number of replies: 2

Hi all,

I'm developing a plugin, which for I need some tables. One of those doesn't need an id column, in my data model, so I didn't add it to the DDL. But now, if I try to insert a record using:

$DB->insert_record()
I get an error: "ERROR: column "id" does not exist".

In install.xml, I have defined something like:
<TABLE NAME="mytable">
      <FIELDS>
        <FIELD NAME="userid" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false"/>
        <FIELD NAME="courseid" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="false"/>
        <FIELD NAME="year" TYPE="int" LENGTH="4" NOTNULL="true" SEQUENCE="false"/>
      </FIELDS>
      <KEYS>
        <KEY NAME="primary" TYPE="primary" FIELDS="userid, courseid"/>
        <KEY NAME="userid_fk" TYPE="foreign" FIELDS="userid" REFTABLE="user" REFFIELDS="id"/>
        <KEY NAME="courseid_fk" TYPE="foreign" FIELDS="courseid" REFTABLE="course" REFFIELDS="id"/>
      </KEYS>
    </TABLE>

And I try the insertion with the following code, following the DML API for inserting records:

$record = new stdClass();

$record->userid = $userid;
$record->courseid = $courseid;
$record->year = $year;

$DB->insert_record('mytable', $record);

And I get the error I mentioned above.

I didn't see anything about this in the DDL API.

So, is it completely necessary to have an 'id' column?


Thanks in advice,

Julen

Average of ratings: -
In reply to Julen Pardo

Re: Inserting rows in tables that don't have 'id' column

by Darko Miletić -

It is highly recommended to have id column but not absolutely required.

Check this post for alternatives:

https://moodle.org/mod/forum/discuss.php?d=326132#p1311833

Average of ratings: Useful (1)
In reply to Darko Miletić

Re: Inserting rows in tables that don't have 'id' column

by Julen Pardo -

Hi Darko,

Thanks a lot for your solution.

I will consider in future developments to add an id column even if the primary key another column or columns.