Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Can I use functions on insert or update? #709

Answered by ahmad-moussawi
finehotdog asked this question in Q&A
Discussion options

I want to do something like the following in SQL Server.

INSERT INTO table (id, name, createAt) values ('0001', 'John', GETDATE() )
( GETDATE is an example and I would like to use it in another function. )

I think you can use "WhereRaw" for "SELECT", but "Raw" cannot be used for INSERT.
var query = new Query("table").WhereRaw("createAt=GETDATE()").Select("name")

Please tell me how to use functions in "Insert" and "Update".

You must be logged in to vote

You are looking for UnsafeLiteral , this is similar to what DB:raw provide on Laravel.

var query = new Query("MyTable").AsUpdate(new
{
 Name = "The User",
 Address = new UnsafeLiteral("@address")
});

Replies: 2 comments 2 replies

Comment options

Hello!

To perform INSERT and UPDATE operations with specific functions in SQL Server, you can use the GETDATE() functions and other functions within SQL queries in Laravel

//Insert
use Illuminate\Support\Facades\DB;
DB::table('table')->insert([
 'id' => '0001',
 'name' => 'John',
 'createAt' => DB::raw('GETDATE()')
]);
//Update
use Illuminate\Support\Facades\DB;
DB::table('table')
 ->where('id', '0001')
 ->update([
 'name' => 'NuevoNombre',
 'createAt' => DB::raw('GETDATE()')
 ]);

I assume you are using Eloquent and Laravel's Query Builder. If you are using a specific Eloquent model for your table, you can also use methods like create or update instead of DB::table.

You must be logged in to vote
1 reply
Comment options

Thank you for answering.
That's exactly what I want to do.

However, the query builder I'm using uses sqlkata, not Laravel.

I would like to know how to achieve that using sqlkata.

Comment options

You are looking for UnsafeLiteral , this is similar to what DB:raw provide on Laravel.

var query = new Query("MyTable").AsUpdate(new
{
 Name = "The User",
 Address = new UnsafeLiteral("@address")
});
You must be logged in to vote
1 reply
Comment options

Thank you!
My long-standing problem has been solved.
I think I'll sleep well tonight.

Thank you everyone.

Answer selected by finehotdog
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

AltStyle によって変換されたページ (->オリジナル) /