Z
Z
Z_Coder2014-04-02 14:12:26
Yii
Z_Coder, 2014-04-02 14:12:26

How to get the id of a newly added entry?

Hello. There is a model and an Order table. I write data to it:

$order = new Order();
$order->amount = Goods::model()->findByPk($goods_id)->price;
$order->order_date = Date('Y.m.d');
$order->save();

Further in the code, you need to use the id of this most added record. I usually just used $order->order_id. For reasons not clear to me, $order->order_id stopped storing the required id, i.e. he now does not store anything at all.
What other ways are there to get the id of the currently added record? And why do you think $order->order_id stopped working?
Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
enchikiben, 2014-04-02
@Z_Coder

Has the record been added to the database? maybe a validation error or a sql error.
also see what $order->save() returns, true/false

D
Dmitry Voronkov, 2014-04-07
@DmitryVoronkov

$order->getPrimaryKey();
But, you may have an exception in this place if the record is not found. Better this way:

$goods = Goods::model()->findByPk($goods_id);
if ( $goods != null) {
    $order = new Order();
    $order->amount = ->$goods->price;
    $order->order_date = Date('Y.m.d');
    $order->save();
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question