Running raw sql inside Model: Laravel

I am using Laravel and you need to run a raw SQL query from the Model / Repository class

INSERT INTO calendar (room_id, date, default_count, default_price) VALUES ('1', '2017-01-02', '2', '400004') ON DUPLICATE KEY UPDATE default_count = VALUES(default_count), default_price = VALUES(default_price); 

ex. When I insert data from UserRepository

 $this->users->insert(['email' => ' john@example.com ', 'votes' => 0]); 

I need some method to connect to DB and run sql through model

 //Something like $this->users->execute($sql); 

I saw that Laravel has an updateOrInsert() method, but I need to run it on multiple datasets at once.

How to run a raw SQL query through a model class or repository?

thanks

UPDATED - SOLVED

I went through the Eloquent Model Sourcecode and found that I could get the connection from the getConnection () method

 $this->users->getConnection()->statement($sql); 
+5
source share
2 answers

I went through the Eloquent Model Sourcecode and found that I could get the connection from the getConnection () method

 $this->users->getConnection()->statement($sql); 

I don’t know that instruction () is the best way to run this sql. However, this worked.

Thank you all for your help. Also, if you have a better solution, let me know

0
source

Do it like

 $query = array(['room_id' => 1, 'date' => '2/1/2017', 'default_count' => '2', 'default_price' => '400004'], ['room_id' => 2, 'date' => '2/1/2017', 'default_count' => '3', 'default_price' => '455004']); DB::table('calendar')->insart('query'); 

And you can also do this, Create an obj of your modal and assign values

 $obj_calendar = new Calendar(); $obj_calendar->room_id = 1; $obj_calendar->date = date('Ymd H:i:s', strtotime('2017-01-02')); $obj_calendar->default_count = 2; $obj_calendar->default_price = 400004; $obj_calendar->save(); 

Transaction Usage

// start the transaction

 public function beginTransaction() { DB::beginTransaction(); } 

// make a transaction

 public function makeTransaction($query) { DB::transaction(function($query) use($query) { DB::insert($query); }); } 

// commit transaction

 public function commitTransaction() { return DB::commit(); } 

In your method

 public function insert($data) { $this->beginTransaction(); for($i=0; $i<count($data); $i++) { $name = $data[$i]->first_name, "middle_name" => $data[$i]->middle_name, "last_name" => $data[$i]->last_name; $query = "INSERT INTO tbl_name(id, first_name, description, created_at, updated_at) VALUES (" . $data[$i]->id . ", " . $name . ", '" . $data[$i]->description . "', '" . date("Ymd H:i:s",strtotime($data[$i]->created_at)) . "', '" . date("Ymd H:i:s",strtotime($data[$i]->created_at)) . "'); "; $scraper_service->makeTransaction($query); } //Add last commit $this->commitTransaction(); } 
0
source

Source: https://habr.com/ru/post/1260988/


All Articles