问题
This post is to sort-of inform and ask a question. Hello all, I'm developing a large system that puts triggers to good use. We're currently running the server-side on Laravel 5.2 with php 7 using phpmyadmin. Within Laravel there isn't really much solid documentation on how to use a trigger through migrations and from what I've discovered you mostly have to do it "raw".
Below is a simple example, that I know of, on how to write a trigger in a migration:
class CreateAccountTriggerTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::unprepared('
CREATE TRIGGER `my_trigger_name` AFTER INSERT ON `table_the_change_happened`
FOR EACH ROW
BEGIN
INSERT INTO `this_table`
(field1,field2,field3)
VALUES
('value1','value2','value3')
END
');
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
DB::unprepared('DROP TRIGGER IF EXISTS `my_trigger_name`');
}
}
The Question: Does anyone know of a clean way to use variables within laravel's query builder?
The method DB::unprepared() does not allow you to attach bound items to it. Trying it in Eloquent is near impossible as there is no solid documentation that I've found for this issue. If anyone can elaborate on this I would greatly appreciate it. Thank you in advance
Update Per request here would be an example of what I mean by using a variable within laravel's query builder:
$stuff = bcrypt($random_numbers);
DB::unprepared('
CREATE TRIGGER `my_trigger_name` AFTER INSERT ON `table_the_change_happened`
FOR EACH ROW
BEGIN
INSERT INTO `this_table`
(field1,field2,field3)
VALUES
('value1','value2','value3',"$stuff")
END
');
回答1:
Unless I'm misunderstanding your question, I think you're looking for the statement()
method, instead of the unprepared()
method. The statement()
method takes a query and an array of parameter bindings for that query.
Example below. The ?
in the values list is the query parameter. The value to bind to that parameter is added to an array passed in the second parameter to the statement()
method.
$stuff = bcrypt($random_numbers);
DB::statement('
CREATE TRIGGER `my_trigger_name` AFTER INSERT ON `table_the_change_happened`
FOR EACH ROW
BEGIN
INSERT INTO `this_table`
(field1,field2,field3)
VALUES
('value1','value2','value3',?)
END
', [$stuff]);
来源:https://stackoverflow.com/questions/39177303/laravel-5-x-database-triggers-and-possible-best-practices