在没有laravel db设置的情况下返回插入ID
I have a database that was not designed for Laravel. I am building a small api using Laravel. Thus I can not useLlaravel structured queries. The query is working but need to be able to retrieve the id number of an insert.
This is the insert I am using.
$results = DB::insert("
SELECT * FROM insrdata.add_user(
:assocID,
:accountID,
:firstName,
:middleName,
:lastName,
:address1,
:address2,
:city,
:state,
:zipCode,
:phone,
:email,
:birthDateMMDDYYYY,
:gradeLevelID,
:commentText
)
",
[
'assocID' => $request->input('assocID'),
'accountID' => $request->input('accountID'),
'firstName' => $request->input('firstName'),
'middleName' => $request->input('middleName'),
'lastName' => $request->input('lastName'),
'address1' => $request->input('address1'),
'address2' => $request->input('address2'),
'city' => $request->input('city'),
'state' => $request->input('state'),
'zipCode' => $request->input(''),
'phone' => $request->input(''),
'email' => $request->input('email'),
'birthDateMMDDYYYY' => $request->input('birthDateMMDDYYYY'),
'gradeLevelID' => $request->input('gradeLevelID'),
'commentText' => $request->input('commentText')
]
);
if($results) {
$return_array = array(
'p_contact_id' => "",
'p_result' => "O.K."
);
}
I need to get the id of the insert.
I think if the insert is successful, you can query for it by accountID (which i suppose unique for each inssured person) and get its id.
This is a little complex without using the Laravel structured queries, as you said. If you can tweak your query a little, and make sure you validate the input data ahead of your insert to prevent SQL injection, you should be able to use insertGetId
. You'll have to do some work, but something along the lines of:
$id = DB::table('whateverYourTableNameIs')->insertGetId([
'assocID' => $request->input('assocID'),
'yourSelectField' => DB::raw("yourRawSelect"),
// etc.
]);
This is called "getting last inserted id". Here documentation in Laravel about it.
https://laravelcode.com/post/laravel-55-get-last-inserted-id-with-example