laravel/php,从sql-pdo中获取选定的ID,并在将来的调用中将其用作变量



我有一个Laravel函数,我在db2上运行一个相当简单的SQL查询,我在插入时选择新创建的记录的id,如下所示:

$sql = " select imaget_id from NEW TABLE (
INSERT INTO IMAGE (name, description, url, image_typet_id)
VALUES (:commonName, :type, :imageZoneName,
(select image_typet_id from image_typet where name = :imageZoneDescription))
); " 
$pdoStatement = $this->pdo->prepare($sql);
foreach ($imageZoneNames as $images) {
$pdoStatement->bindParam(':commonName',           $commonName            );
$pdoStatement->bindParam(':type',                 $type                  );
$pdoStatement->bindParam(':imageZoneName',        $images['name']);
$pdoStatement->bindParam(':imageZoneDescription', $images['desc']);
$pdoStatement->execute();
//I'll need the Image ID here
}

insert本身工作起来没有任何问题,但我需要获取所选的ID,并在执行后将其用作另一个调用的参数。因此,如果我的插入返回id123,我将需要它作为$newId这样的变量

如何正确地使用这个新生成和选择的ID,并在执行语句后将其用作自己的变量?

使用Eloquent可以非常容易地实现这一点
您需要两种型号:

php artisan make:model Image
php artisan make:model ImageTypet

有关配置模型的详细信息,请单击此处。

在控制器中导入您的模型:

use AppImage;
use AppImageTypet;

在你的控制器方法:

foreach ($imageZoneNames as $images) {
$typetId = ImageTypet::where('name', $images['desc'])->value('image_typet_id');
$imageModel = new Image;

$imageModel->name            = $commonName;
$imageModel->description     = $type;
$imageModel->url             = $images['name'];
$imageModel->image_typet_id  = $typetId;
$imageModel->save()
$imageId = $imageModel->id //Here's your ID, immediately available after save().
}

相关内容

最新更新