简体   繁体   中英

CodeIgniter MSSQL get last_id() of composite primary key

I am working on an application for our company that requires a composite primary key.

Per the requirements, the composite is made up of RegionID and AuthorizationID but AuthroizationID does not need to be unique to itself. In other words they want it to do this:

RegionID    AuthorizationID
300         1
300         2
100         1

So I can't create a simple Identity on Authorization then just stick RegionID on the front. (Believe me I tried my best to not make it this way)

Anyway, I created an INSERT trigger in MSSQL 2008 that that OUTPUTs the newly inserted RegionID and AuthorizationID, and encapsulated it in dbo.vwCreateRA. It works great in MSSQL Studio.

However to make it at all usable, I want to be able to get the Composite PK back from an insert inside codeigniter, to redirect the user to the newly created record.

$sql = "INSERT INTO ReturnAuthorizations.dbo.vwCreateRA (
                    [Region],
                    [CustomerNumber],
                    /* a bunch of other fields... */
                    [UserID]
                )
            VALUES
                ?,
                ?,
                /* a bunch of other values */
                ?)";

    $query = $this->db->query($sql, [
        $customer['SalespersonNumber'],
        $customer['CustomerName'],
        /* A bunch of other variables... */
        $username
    ]);

    die(var_dump($query->last_id());

Gives me: Fatal error: Call to a member function last_id() on a non-object

How can I grab the OUTPUT from the view's INSERT through CodeIgniter, or will I have to rely on something like:

(Please excuse the code, probably not best practices, only intended to make the point of the query)

$sql = "SELECT TOP 1
        RegionID,
        Authorization
    FROM
        AuthorizationTable
    WHERE
        RegionID = " . $customer['Region'] . "
        AND UserID = " . $username . "
    ORDER BY
        CreateDate DESC";

Thanks!

You should use $this->db->insert_id();

Replace

$query->last_id();

with

$this->db->insert_id(); 

UPDATE :

your select query should be like this :

$sql = "SELECT TOP 1 RegionID, Authorization 
        FROM AuthorizationTable 
        WHERE RegionID = '" . $customer['Region'] . "' AND UserID = '" . $username . "'  
        ORDER BY  CreateDate DESC";

See here : https://www.codeigniter.com/user_guide/database/helpers.html#information-from-executing-a-query

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM