我无法在 laravel 7 项目中获得最后一个插入 ID
Posted
技术标签:
【中文标题】我无法在 laravel 7 项目中获得最后一个插入 ID【英文标题】:I cant get lastInsertId on laravel 7 project 【发布时间】:2022-01-16 02:37:21 【问题描述】:$sql = DB::table('laravel_products')
->insert(array(
'name' => $name,
'price' => $price,
'qty' => $qty,
'description' => $description,
'uruu' => $uruu,
'garage' => $garage,
'duureg' => $duureg,
'tagt' => $tagt,
'talbai' => $talbai,
'haalga' => $haalga,
'tsonh' => $tsonh,
'shal' => $shal,
'tsonhtoo' => $ttsonh,
'hdawhar' => $bdawhar,
'lizing' => $lizing,
'utas' => $utas,
'email' => $email,
'hereg' => $hereg,
'bairshil' => $bairshil,
'bairlal' => $bairlal,
'ashig' => $ashigon,
'zahi' => $zahi,
'image' => $data
));
$lastInsertedID = $sql->lastInsertId();
当我尝试插入它的响应时:
"在 bool 上调用成员函数 lastInsertId()"
我用了insertGetId
,但是它不能在mysql上保存多行图片。
【问题讨论】:
Welcome to SO ...insert
方法不返回您可以调用方法的对象,它返回一个 bool
..,您可以从连接中获取底层 PDO 实例并在其上调用该方法:DB::getPdo()->lastInsertId()
谢谢,它的获取 id 和产品表 id 和图像表 id 现在是相同的,但看起来没有链接,可以吗?
idk 你所说的链接是什么意思,你在这里将一条记录插入到一个表中
现在我编辑了主帖,感谢您的帮助^^这里是图片和代码
感谢您帮助我^^
【参考方案1】:
如果您想获取最后插入的 ID,您可以直接在 PDO
实例上调用该方法:
$id = DB::getPdo()->lastInsertId();
【讨论】:
【参考方案2】:如果表有自增id,使用insertGetId方法插入一条记录,然后取回ID:
$id = DB::table('users')->insertGetId(
['email' => 'john@example.com', 'votes' => 0]
);
来自:https://laravel.com/docs/5.8/queries#inserts
【讨论】:
【参考方案3】: $data = new LaravelProducts(); //LaravelProducts is your Model Name
$data->name= $name; //here 'name' is your column name
$data->price= $price; //here 'price' is your column name
$data->qty= $qty; //here 'qty' is your column name
$data->description= $description; //here 'description' is your column name
..........
..........
$data->image= $image; //here 'image' is your column name
$data->save();
$lastInsertedId = $data->id;
【讨论】:
【参考方案4】:您不必编写新查询来从数据库中收集最后插入的 id。
$laravel_product = DB::table('laravel_products')
->insertGetId( array(
'name' => $name,
'price' => $price,
'qty' => $qty,
'description' => $description,
'uruu' => $uruu,
'garage' => $garage,
'duureg' => $duureg,
'tagt' => $tagt,
'talbai' => $talbai,
'haalga' => $haalga,
'tsonh' => $tsonh,
'shal' => $shal,
'tsonhtoo' => $ttsonh,
'hdawhar' => $bdawhar,
'lizing' => $lizing,
'utas' => $utas,
'email' => $email,
'hereg' => $hereg,
'bairshil' => $bairshil,
'bairlal' => $bairlal,
'ashig' => $ashigon,
'zahi' => $zahi,
'image' => $data
)
);
foreach ($filenamesToSave as $filename)
DB::insert('INSERT INTO laravel_products_images ( product_id, filename ) VALUES ( ?, ? )',[$laravel_product->id, $filename]);
return view('createproduct');
// Foreach Closing
// Echo your inserted ID Like Below
echo $laravel_product->id;
它应该 100% 为您工作。
【讨论】:
no ...insert
返回 bool
github.com/laravel/framework/blob/8.x/src/Illuminate/Database/…
insertGetId
返回一个 'id' (int) 而不是一个对象以上是关于我无法在 laravel 7 项目中获得最后一个插入 ID的主要内容,如果未能解决你的问题,请参考以下文章
VSCode Intellisense 无法在 Laravel 项目中正常工作