Laravel 4 - 返回当前插入的ID

7
我有以下查询。
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?

谢谢。


DB::getPdo()->lastInsertId() - jrsalunga
4个回答

13

为什么不创建一个模型,而不是进行原始查询...

称之为Conversation或其他名称...

然后你就可以直接这样做...

 $result = Conversation::create(array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now ))->id;

如果你使用的是Laravel 4,你可以使用insertGetId方法...在Laravel 3中是insert_get_id(),它将返回一个id

 $results = DB::table('pm_conversations')->insertGetId(
    array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);

这种方法需要表的id是自增的,因此要注意这一点...

最后一种方法是,你可以返回最后插入的mysql对象....

就像这样...

 $result = DB::connection('mysql')->pdo->lastInsertId();

所以如果你选择了最后那条路...

它会继续前进...

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。


我正在使用Laravel 4... 我尝试将->insert更改为->insertGetId并保持一切不变,但它没有返回ID...除了return $results之外,我需要做些什么吗? - BigJobbies
就像我之前提到的,对话表上的id是自增的吗?如果是,该方法期望这样,否则最安全的方法就是直接从mysql返回最新的PDO插入。 - Kylie
当您在返回之前var_dump($results)会发生什么?它显示了什么? - Kylie
是的,它正在自动递增... 它运行得很完美,我只是在我的错误检查中被卡住了。谢谢 :) - BigJobbies

13
你可以使用 DB::getPdo()->lastInsertId()

我认为这是最好的方式,谢谢。getPdo()是什么? - Mohammad Kermani

10

使用 Eloquent,您可以进行以下操作:

$new = Conversation();
$new->currentId = $currentId;
$new->toUserId = $toUserId;
$new->ip = Request::getClientIp();
$new->time = $now;

$new->save();

$the_id = $new->id; //the id of created row

0
我让它工作的方式是运行一个插入语句,然后返回插入的行ID(这是一个自学发票项目)。
        WorkOrder::create(array(
        'cust_id' => $c_id,
        'date' => Input::get('date'),
        'invoice' => Input::get('invoice'),
        'qty' => Input::get('qty'),
        'description' => Input::get('description'),
        'unit_price' => Input::get('unit_price'),
        'line_total' => Input::get('line_total'),
        'notes'     => Input::get('notes'),
        'total' => Input::get('total')
    ));

    $w_id = WorkOrder::where('cust_id', '=', $c_id)->pluck('w_order_id');
    return $w_id;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接