douguwo2275 2018-06-08 14:02
浏览 71
已采纳

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

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!

  • 写回答

1条回答 默认 最新

  • dtlh12053 2018-06-08 14:07
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改