Larabel Altural을 사용하여 마지막으로 삽입된 ID 가져오기
현재 아래 코드를 사용하여 테이블에 데이터를 삽입하고 있습니다.
<?php
public function saveDetailsCompany()
{
$post = Input::All();
$data = new Company;
$data->nombre = $post['name'];
$data->direccion = $post['address'];
$data->telefono = $post['phone'];
$data->email = $post['email'];
$data->giro = $post['type'];
$data->fecha_registro = date("Y-m-d H:i:s");
$data->fecha_modificacion = date("Y-m-d H:i:s");
if ($data->save()) {
return Response::json(array('success' => true), 200);
}
}
마지막으로 삽입한 신분증을 반납하고 싶은데 어떻게 발급받는지 모르겠어요.
잘 부탁드립니다!
저장 후$data->id
아이디
$data->save();
$data->id;
이렇게 사용할 수 있습니다.
return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);
업데이트된 라라벨 버전은 다음을 참조하십시오.
return response()->json(array('success' => true, 'last_insert_id' => $data->id), 200);
이 경우 xdazz가 옳습니다만, 향후의 방문자를 위해서라면DB::statement
★★★★★★★★★★★★★★★★★」DB::insert
, 다른 방법이 있습니다.
DB::getPdo()->lastInsertId();
테이블에 자동 증분 ID가 있는 경우 insertGetId 메서드를 사용하여 레코드를 삽입하고 ID를 가져옵니다.
$id = DB::table('users')->insertGetId([
'email' => 'john@example.com',
'votes' => 0
]);
참조: https://laravel.com/docs/5.1/queries#inserts
에 드는 을 Model::create()
각 하지 않고 Laracasts 5를 합니다.$fillable
대량 할당의 경우(이 방법을 사용하는 신규 사용자에게 매우 중요):는 많은 .insertGetId()
하지만 불행히도 이것은 이 문제를 존중하지 않는다.$fillable
화이트리스트를 사용하면 _filters 및 데이터베이스에 필드가 아닌 항목을 삽입하려고 할 때 오류가 발생하거나 필터링할 항목을 설정할 수 있습니다.가능하면 일괄 할당으로 코드를 적게 쓰고 싶기 때문에 실망했습니다.다행히 Archental의 메서드는 (@xdazz가 위에서 인용한) 저장 메서드를 감싸고 있기 때문에 마지막으로 작성한 ID를 가져올 수 있습니다.
public function store() {
$input = Request::all();
$id = Company::create($input)->id;
return redirect('company/'.$id);
}
*** 라라벨용****
먼저 개체를 만들고 다음으로 해당 개체의 속성 값을 설정한 다음 개체 레코드를 저장한 다음 다음과 같은 마지막으로 삽입된 ID를 가져옵니다.
$user = new User();
$user->name = 'John';
$user->save();
// 마지막으로 삽입된 ID 가져오기 중
$insertedId = $user->id;
echo $insertedId ;
마지막으로 삽입된 ID를 가져오는 방법은 여러 가지가 있습니다.모두 삽입할 때 어떤 방법을 사용했느냐에 따라 달라집니다.이 경우 다음과 같은 마지막 ID를 얻을 수 있습니다.
$data->save();
$data->id;
여기서 다른 삽입 방법을 사용하는 경우 마지막으로 삽입된 ID를 얻는 방법을 알아야 하는 다른 사용자에게는 다음과 같은 방법이 있습니다.
「」를 사용합니다.
create()
$book = Book::create(['name'=>'Laravel Warrior']);
$lastId = $book->id;
「」를 사용합니다.
insertGetId()
$id = DB::table('books')->insertGetId( ['name' => 'Laravel warrior'] ); $lastId = $id;
「」를 사용합니다.
lastInsertId()
$lastId = DB::getPdo()->lastInsertId();
레퍼런스 https://easycodesolution.com/2020/08/22/last-inserted-id-in-laravel/
larabel 5에서는 다음과 같이 할 수 있습니다.
use App\Http\Requests\UserStoreRequest;
class UserController extends Controller {
private $user;
public function __construct( User $user )
{
$this->user = $user;
}
public function store( UserStoreRequest $request )
{
$user= $this->user->create([
'name' => $request['name'],
'email' => $request['email'],
'password' => Hash::make($request['password'])
]);
$lastInsertedId= $user->id;
}
}
이것은 4.2 라라벨에서 나에게 효과가 있었다.
$id = User::insertGetId([
'username' => Input::get('username'),
'password' => Hash::make('password'),
'active' => 0
]);
다음은 예를 제시하겠습니다.
public static function saveTutorial(){
$data = Input::all();
$Tut = new Tutorial;
$Tut->title = $data['title'];
$Tut->tutorial = $data['tutorial'];
$Tut->save();
$LastInsertId = $Tut->id;
return Response::json(array('success' => true,'last_id'=>$LastInsertId), 200);
}
insertGetId
id
동시에
테이블에 자동 증분 ID가 있는 경우 insertGetId 메서드를 사용하여 레코드를 삽입하고 ID를 가져옵니다.
타고Model
$id = Model::insertGetId(["name"=>"Niklesh","email"=>"myemail@gmail.com"]);
타고DB
$id = DB::table('users')->insertGetId(["name"=>"Niklesh","email"=>"myemail@gmail.com"]);
상세한 것에 대하여는, https://laravel.com/docs/5.5/queries#inserts 를 참조해 주세요.
여기 라라벨 4에서 마지막으로 삽입된 ID를 얻을 수 있는 방법이 있습니다.
public function store()
{
$input = Input::all();
$validation = Validator::make($input, user::$rules);
if ($validation->passes())
{
$user= $this->user->create(array(
'name' => Input::get('name'),
'email' => Input::get('email'),
'password' => Hash::make(Input::get('password')),
));
$lastInsertedId= $user->id; //get last inserted record's user id value
$userId= array('user_id'=>$lastInsertedId); //put this value equal to datatable column name where it will be saved
$user->update($userId); //update newly created record by storing the value of last inserted id
return Redirect::route('users.index');
}
return Redirect::route('users.create')->withInput()->withErrors($validation)->with('message', 'There were validation errors.');
}
insert()의 경우
예:
$data1 = array(
'company_id' => $company_id,
'branch_id' => $branch_id
);
$insert_id = CreditVoucher::insert($data1);
$id = DB::getPdo()->lastInsertId();
dd($id);
비록 이 질문은 좀 구식이긴 하지만.빠르고 지저분한 솔루션은 다음과 같습니다.
$last_entry = Model::latest()->first();
하지만 자주 찾는 데이터베이스의 인종 조건에 취약할 것 같아요
모델을 저장한 후 초기화된 인스턴스의 ID는 다음과 같습니다.
$report = new Report();
$report->user_id = $request->user_id;
$report->patient_id = $request->patient_id;
$report->diseases_id = $request->modality;
$isReportCreated = $report->save();
return $report->id; // this will return the saved report id
마지막으로 삽입된 레코드 ID를 쉽게 가져올 수 있습니다.
$user = User::create($userData);
$lastId = $user->value('id');
DB에 마지막으로 삽입된 레코드에서 Id를 가져오는 것은 놀라운 기술입니다.
끝나고
$data->save()
$data->id
삽입된 ID가 표시됩니다.
주의: 자동 증분 열 이름이 sno인 경우 다음을 사용해야 합니다.$data->sno
가 아니라$data->id
데이터베이스에 레코드를 저장한 후 다음 방법으로 ID에 액세스할 수 있습니다.$data->id
return Response::json(['success' => true, 'last_insert_id' => $data->id], 200)
Laravel 5.2에서는 가능한 한 깨끗하게 합니다.
public function saveContact(Request $request, Contact $contact)
{
$create = $contact->create($request->all());
return response()->json($create->id, 201);
}
라라벨의 경우, 새로운 레코드를 삽입하고$data->save()
이 함수는 INSERT 쿼리를 실행하고 기본 키 값(기본값으로는 id)을 반환합니다.
사용할 수 있는 코드는 다음과 같습니다.
if($data->save()) {
return Response::json(array('status' => 1, 'primary_id'=>$data->id), 200);
}
다음과 같이 할 수 있습니다.
$result=app('db')->insert("INSERT INTO table...");
$lastInsertId=app('db')->getPdo()->lastInsertId();
$objPost = new Post;
$objPost->title = 'Title';
$objPost->description = 'Description';
$objPost->save();
$recId = $objPost->id; // If Id in table column name if other then id then user the other column name
return Response::json(['success' => true,'id' => $recId], 200);
데이터베이스에 마지막으로 삽입된 ID를 가져오려면 다음을 사용할 수 있습니다.
$data = new YourModelName;
$data->name = 'Some Value';
$data->email = 'abc@mail.com';
$data->save();
$lastInsertedId = $data->id;
여기서 $lastInsertedId는 마지막으로 삽입된 자동 증가 ID를 제공합니다.
가장 짧은 방법은 아마도 모델상의 콜일 것입니다.
public function create(array $data): MyModel
{
$myModel = new MyModel($dataArray);
$myModel->saveOrFail();
return $myModel->refresh();
}
다음과 같이 시도할 수도 있습니다.
public function storeAndLastInrestedId() {
$data = new ModelName();
$data->title = $request->title;
$data->save();
$last_insert_id = $data->id;
return $last_insert_id;
}
저는 이렇게 동작하고 있습니다.family_id는 자동 증분을 사용하는 프라이머리 키입니다.Laravel7을 사용하고 있습니다.
public function store(Request $request){
$family = new Family();
$family->family_name = $request->get('FamilyName');
$family->family_no = $request->get('FamilyNo');
$family->save();
//family_id is the primary key and auto increment
return redirect('/family/detail/' . $family->family_id);
}
또한 Model을 확장한 Model Family 파일에서는 증가분을 true로 설정해야 합니다.그렇지 않으면 위의 $family_id가 빈 상태로 반환됩니다.
public $incrementing = true;
웅변 모델 사용
$user = new Report();
$user->email= 'johndoe@example.com';
$user->save();
$lastId = $user->id;
쿼리 작성기 사용
$lastId = DB::table('reports')->insertGetId(['email' => 'johndoe@example.com']);
저장 후$data->save()
모든 데이터가 내부로 푸시됩니다.$data
이것은 오브젝트이며 현재 행은 최근에 저장되어 있기 때문에$data
마지막insertId
안에서 발견되다$data->id
.
응답 코드는 다음과 같습니다.
return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);
마지막으로 삽입된 ID는 저장 메서드라고 하는 동일한 오브젝트로 얻을 수 있습니다.
$data->save();
$inserted_id = $data->id;
다음과 같이 간단하게 쓸 수 있습니다.
if ($data->save()) {
return Response::json(array('success' => true,'inserted_id'=>$data->id), 200);
}
public function store( UserStoreRequest $request ) {
$input = $request->all();
$user = User::create($input);
$userId=$user->id
}
웅변 모델 사용
use App\Company;
public function saveDetailsCompany(Request $request)
{
$createcompany=Company::create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);
// Last Inserted Row ID
echo $createcompany->id;
}
쿼리 작성기 사용
$createcompany=DB::table('company')->create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);
echo $createcompany->id;
Larabel에서 Last Inserted Row ID를 취득하는 방법에 대한 자세한 내용은http://http://phpnotebook.com/95-laravel/127-3-methods-to-get-last-inserted-row-id-in-laravel 를 참조해 주세요.
언급URL : https://stackoverflow.com/questions/21084833/get-the-last-inserted-id-using-laravel-eloquent
'itsource' 카테고리의 다른 글
TokuDB 쿼리에서 임시 테이블을 만드는 속도가 너무 느립니다. (0) | 2022.11.24 |
---|---|
Java에는 Integer, Float, Double, Long의 가변형이 있습니까? (0) | 2022.11.24 |
Android의 AsyncTask에서 값 반환 (0) | 2022.11.24 |
느린 SecureRandom 제너레이터에 대처하는 방법 (0) | 2022.11.24 |
인터페이스에는 스태틱메서드가 없지만 스태틱필드와 내부 클래스는 정상인 이유는 무엇입니까?[Java8 이전] (0) | 2022.11.24 |