CodeIgniter MSSQL获取复合主键的last_id()

时间:2018-06-08 14:02:04

标签: php codeigniter sql-server-2008 composite-primary-key

我正在为需要复合主键的公司申请。

根据要求,复合材料由RegionID和AuthorizationID组成,但AuthroizationID不需要对其自身唯一。换句话说,他们希望它这样做:

RegionID    AuthorizationID
300         1
300         2
100         1

所以我无法在授权上创建一个简单的身份,然后将RegionID粘贴在前面。 (相信我,我尽力不这样做)

无论如何,我在MSSQL 2008中创建了一个INSERT触发器,它输出新插入的RegionID和AuthorizationID,并将其封装在dbo.vwCreateRA中。它在MSSQL Studio中运行良好。

然而,为了使它完全可用,我希望能够从codeigniter中的插入中获取Composite PK,以将用户重定向到新创建的记录。

$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());

给我: Fatal error: Call to a member function last_id() on a non-object

如何通过CodeIgniter从视图的INSERT中获取OUTPUT,或者我必须依赖以下内容:

(请原谅代码,可能不是最佳做法,只是为了明确查询)

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

谢谢!

1 个答案:

答案 0 :(得分:1)

您应该使用$this->db->insert_id();

替换

$query->last_id();

$this->db->insert_id(); 

更新:

您的选择查询应如下所示:

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

见这里:https://www.codeigniter.com/user_guide/database/helpers.html#information-from-executing-a-query