Laravel 4-返回当前插入的ID [英] Laravel 4 - Return the id of the current insert
问题描述
我有以下查询
public static function createConversation( $toUserId )
{
$now = date('Y-m-d H:i:s');
$currentId = Auth::user()->id;
$results = DB::table('pm_conversations')->insert(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
return $results;
}
如何返回刚刚插入的行的ID?
How would i return the id of the row just inserted?
干杯
推荐答案
为什么不创建原始查询,而不创建模型...
Instead of doing a raw query, why not create a model...
将其称为对话"或其他...
Call it Conversation, or whatever...
然后您就可以做....
And then you can just do....
$result = Conversation::create(array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now ))->id;
哪个将返回ID ...
Which will return an id...
或者,如果您使用的是Laravel 4,则可以使用insertGetId方法...在Laravel 3中,我相信它的insert_get_id()
Or if you're using Laravel 4, you can use the insertGetId method...In Laravel 3 its insert_get_id() I believe
$results = DB::table('pm_conversations')->insertGetId(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
此方法要求表的ID为自动递增,因此请注意...
This method requires that the id of the table be auto-incrementing, so watch out for that...
最后一个方法是,您可以只返回最后插入的mysql对象....
The last method, is that you can just return the last inserted mysql object....
就这样...
$result = DB::connection('mysql')->pdo->lastInsertId();
所以,如果您选择最后一条路...
So if you choose that last road...
会...
public static function createConversation( $toUserId )
{
$now = date('Y-m-d H:i:s');
$currentId = Auth::user()->id;
$results = DB::table('pm_conversations')->insert(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
$theid= DB::connection('mysql')->pdo->lastInsertId();
return $theid;
}
我个人选择创建实际模型的第一种方法.这样,您实际上可以拥有所讨论项目的对象. 然后,不创建模型而是只保存()....您调用YourModel :: create(),这将返回最新模型创建的ID
I would personally choose the first method of creating an actual model. That way you can actually have objects of the item in question. Then instead of creating a model and just save()....you calll YourModel::create() and that will return the id of the latest model creation
这篇关于Laravel 4-返回当前插入的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!