Laravel:InsertgetId 并显示结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24926755/
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
Laravel: InsertgetId and display results
提问by Onetest
I would like to insert some records into my DB table and using the insertgetid feature, return those results to my blade view.
我想在我的数据库表中插入一些记录并使用 insertgetid 功能,将这些结果返回到我的刀片视图。
Controller
控制器
$grids[] = array();
foreach($c as $key) {
$grids[] = DB::table('infile')->insertGetId(
array( 'href' => $key,
'creator_id' => $id,
'random' => substr(str_shuffle("aBcEeFgHiJkLmNoPqRstUvWxYz0123456789"),0, 9))
);
}
$name[] = array();
foreach($grids as $id){
$name = DB::table('infile')->where('id', '=', $id)->first();
}
return View::make('Home')->withName($name);
Blade View
刀片视图
@if(isset($name) && $name != '')
{{dd($name)}}
@endif
I'm getting this error
我收到这个错误
ErrorException
preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
回答by Jarek Tkaczyk
You can use whereIn
to make exact query. between
should work, but it's error prone, since there might be another row inserted in the meantime:
您可以使用whereIn
进行精确查询。between
应该可以工作,但很容易出错,因为在此期间可能插入了另一行:
$ids = [];
foreach (..)
{
$ids[] = DB::table('infile')->insertGetId(...);
}
$data = DB::table('infile')->whereIn('id', $ids)->get();
回答by Onetest
I ended up using a different approach
我最终使用了不同的方法
I found the max id
before I performed the insert and then found the max id
after the insert and then used a wherebetween to grab the data.
我id
在执行插入之前找到了最大值,然后在插入之后找到了最大值id
,然后使用了中间值来获取数据。
$max = DB::table('infile')->max('id');
foreach($c as $key) {
DB::table('infile')->insertGetId(
array( 'href' => $key,
'creator_id' => $id,
'random' => substr(str_shuffle("aBcEeFgHiJkLmNoPqRstUvWxYz0123456789"),0, 9))
);
}
$max2 = DB::table('infile')->max('id');
$data = DB::table('infile')->whereBetween('id', array($max, $max2))->get();