laravel 如何通过laravel中的save()方法获取最后插入的id
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42806786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get last inserted id through save() method in laravel
提问by Alen
I know to get the last id I can use insertGetId()
but I want to know how can I get the last inserted id through save()
method.
我知道要获取我可以使用的最后一个 ID,insertGetId()
但我想知道如何通过save()
方法获取最后一个插入的 ID 。
order = new Store_order;
$order->invoice_id = $signed['invoice_id'];
$invoice = $order->save()['so_id'];
I used this but it returns null
value
我用过这个,但它返回null
值
回答by TIGER
After $order->save()
, $order->so_id
should be the last id inserted. Your code should be as below.
之后$order->save()
,$order->so_id
应该是最后插入的 id。您的代码应如下所示。
$order = new Store_order;
$order->invoice_id = $signed['invoice_id'];
$order->save();
$invoice = $order->so_id;
回答by Muthu17
You can get it by like below :
您可以通过如下方式获得它:
$order = new Store_order;
$order->invoice_id = $signed['invoice_id'];
$invoice = $order->save();
echo $invoice->so_id;
in this case you no need to store in one variable and then access it, You can get the inserted records by calling the model object itself :
在这种情况下,您无需存储在一个变量中然后访问它,您可以通过调用模型对象本身来获取插入的记录:
$order = new Store_order;
$order->invoice_id = $signed['invoice_id'];
$order->save();
// echo $order; => will return entire stored last record.
echo $order->so_id;
Make sure so_id is autoincrement.
确保 so_id 是自动递增的。
回答by Rashi Goyal
Try this once it worked for me where $mode->save(); was only returning true.
试试这个,一旦它对我有用, $mode->save(); 只是返回true。
$mylastid = DB::getPdo()->lastInsertId();
回答by Intelixence
In case of you did overwride the name of primary key in the model as in next case:
如果您确实在模型中覆盖了主键的名称,如下一种情况:
protected $primaryKey = 'your_table_id_name';
use:
用:
$id = $your_variable_save->your_table_id_name
if not:
如果不:
$id = $your_variable_save->id
回答by Amit Mandaviya
$ObjTable->nane = $name;
$ObjTable->save();
echo $ObjTable->id;
this will be display last inserted id.
这将显示最后插入的 ID。
回答by Majbah Habib
Your May solve the issue by following the given example.
您可以按照给定的示例解决问题。
**** For Laravel ****
**** 对于 Laravel ****
$order = new Store_order();
$order->invoice_id = $signed['invoice_id'];
$order->save();
//Getting Last inserted id
$insertedId = $order->so_id;
** provided that $order->so_idmeans, getting store_order table primary key filed so_idvalue.
** 前提是$order->so_id表示,获取 store_order 表主键归档的so_id值。