Laravel provides DB facade (original search), query builder, Eloquent ORM three ways to operate the database 1. Connect to the database .env database configuration DB_HOST=localhost dbhost DB_DATABASE=laravel dbname DB_USERNAME=root username DB_PASSWORD=root password 2. Use DB facade to implement CURD (1) Create a new route Route::get('city', 'cityController@index'); (2) Create a new controller and query it directly in the controller namespace App\Http\Controllers; use Illuminate\Support\Facades\DB; class CityController extends Controller { public function index() { $insert = DB::insert('insert into city set name="安徽",state="init"'); Added: return bool $delete = DB::delete('delete from city where id > 5'); delete: returns the number of rows deleted $update = DB::update('update city set name = "上海" where id = 8'); Change: return the number of rows updated $city = DB::select('select * from city'); Check: return an array } } 3. Use the query builder to implement CURD (1) Add: $insert_bool = DB::table('city')->insert(['name' => '湖南', 'state' => 'init']); Insert a piece of data and return a bool value $insert_id = DB::table('city')->insertGetId(['name' => '湖北', 'state' => 'init']); Insert a piece of data and return the inserted record id $insert_bool = DB::table('city')->insert([['name' => '北京', 'state' => 'init'], ['name' => '上海', 'state' => 'init']]); Insert multiple pieces of data and return bool value (2) delete: $delete_row = DB::table('city')->where('id', 14)->delete(); Delete a record, return the number of rows affected, 1 row $delete_table = DB::table('city')->truncate(); Empty a table without returning any flags (3) Change: $update_row = DB::table('city')->where('id', 20)->update(['name' => '日本']); Update a piece of data to return the number of rows affected, 1 row $update_row = DB::table('carousel')->increment('order_number'); Let the order_number of all records be incremented by 1, and return the number of affected rows, 6 rows $update_row = DB::table('carousel')->decrement('order_number'); Let the order_number of all records be decremented by 1, and return the number of affected rows, 6 rows $update_row = DB::table('carousel')->increment('order_number', 100); Let the order_number of all records be incremented by 100, and return the number of affected rows, 6 rows $update_row = DB::table('carousel')->decrement('order_number', 100); Let the order_number of all records be decremented by 100, and return the number of affected rows, 6 rows $update_row = DB::table('carousel')->where('id', 1)->increment('order_number', 200); Modify the order_number field with a record id of 1 to increment by 200, and return the number of affected rows, 1 row $update_row = DB::table('carousel')->where('id', 1)->increment('order_number', 200, ['name' => 'Auto-increment and modify fields']); Modify the order_number field with a record id of 1 to increment by 200, and modify other fields at the same time, and return the number of affected rows, 1 row (4) Check: $select_rows = DB::table('city')->get(); get method to query all records $first_row = DB::table('carousel')->orderBy('id', 'asc')->first(); The first method queries the first item after sorting $select_rows = DB::table('carousel')->where('id', '>=', 2)->get(); where method queries all records that meet a single condition $select_rows = DB::table('carousel')->whereRaw('id >= ? and order_number > ?', [1, 5])->get(); whereRaw method to query all records that meet multiple conditions $select_field = DB::table('carousel')->pluck('name'); The pluck method queries the name field of each record that meets the conditions $select_field = DB::table('carousel')->lists('name'); $select_field = DB::table('carousel')->lists('name', 'id_code'); The lists method queries the name field of each record that meets the conditions (or query the name field of each record that meets the conditions with id_code as the key name) $select_field = DB::table('carousel')->select('id','id_code','name')->get(); The select method queries the specified field of each record that meets the conditions DB::table('user_log')->chunk(10, function($number){ var_dump($number); if(???) return false; }); The chunk method queries a fixed record each time according to the conditions, and the internal callback function can control the process, and can return false when a certain condition is met dd($select_field); (5) Aggregation function: $count = DB::table('city')->count(); Count the total number of records $max = DB::table('user_log')->max('id'); find the maximum value $min = DB::table('user_log')->min('id'); find the minimum value $avg = DB::table('user_log')->avg('id'); average $sum = DB::table('user_log')->sum('user_id'); sum dd($sum); 4. Implement CURD using Eloquent ORM Introduction: The Eloquent ORM that comes with laravel is a beautiful and concise ActiveRecord implementation used to implement database operations. Each data table has a corresponding model model for interacting with the data table. 1) Introduction, model establishment and query data: routing: Route::any('orm1', ['uses' => 'CityController@orm1']); Controller: namespace App\Http\Controllers; use App\City; class CityController extends Controller { public function orm1() { (1) The all method queries all records $city = City::all(); (2) The find method queries a single record based on the primary key id $city = City::find(1); (3) The findOrFail method queries a single record according to the primary key id, and reports an exception if the query fails $city = City::findOrFail(1); (4) The get method queries all records $city = City::get(); (5) The first method queries the first record $city = City::where('id', '>', 1)->orderBy('id', 'desc')->first(); (6) The chunk method records a fixed number of records per query City::chunk(1, function ($number) { var_dump($number); }); (7) count() method to find the total number of records $count = City::count(); (8) max() method to find the maximum value $max = City::where('id', '>', 1)->max('parent_id');; } } Model: namespace App; use Illuminate\Database\Eloquent\Model; class City extends Model { protected $table = 'city'; // Specify the table name to associate with the model protected $primaryKey = 'id'; // Specify the primary key, the default is id can not be written } 2) Add data, use custom timestamps and batch assignment: routing: Route::any('orm1', ['uses' => 'CityController@orm1']); Controller: namespace App\Http\Controllers; use App\City; class CityController extends Controller { public function orm1() { // add data, save data $city = new City(); $city->name = '123456'; $city->state = 'init'; $bool = $city->save(); dd($bool); // Use the create method of the model to add data $city = City::create(['name' => '南通', 'state' => 'init']); dd($city); // Query data by attribute, if not, create it $city = City::firstOrCreate(['name' => '南通']); // Query data by attributes, if not, create it, but you need to use save to save it $city = City::firstOrNew(['name' => 'Nantong ssss']); $city->save(); dd($city); } } Model: namespace App; use Illuminate\Database\Eloquent\Model; class City extends Model { protected $table = 'city'; // Specify the table name to associate with the model protected $primaryKey = 'id'; // Specify the primary key, the default is id can not be written public $timestamps = false; // Turn off automatic maintenance of timestamps (if changed to true, you need to manually add created_at and updated_at fields in advance, and the time at this time is in datetime format) protected function getDateFormat() // This method can change the datetime type of the created_at and updated_at fields to the timestamp format { return time(); } protected function asDateTime($value) // Do not format the time taken out { return $value; } } 3) Modify the data using Eloquent ORM: routing: Route::any('orm1', ['uses' => 'CityController@orm1']); Controller: namespace App\Http\Controllers; use App\City; class CityController extends Controller { public function orm1() { //update data through model $city = City::find(9); $city->name = 'Suzhou'; $bool = $city->save(); var_dump($bool); //Update data in batches and return the number of updated bars $update_rows = City::where('id', '>', 2)->update(['parent_id' => 10]); var_dump($update_rows); } } Model: namespace App; use Illuminate\Database\Eloquent\Model; class City extends Model { protected $table = 'city'; // Specify the table name to associate with the model protected $primaryKey = 'id'; // Specify the primary key, the default is id can not be written public $timestamps = false; // Turn off automatic maintenance of timestamps (if changed to true, you need to manually add created_at and updated_at fields in advance, and the time at this time is in datetime format) protected function getDateFormat() // This method can change the datetime type of the created_at and updated_at fields to the timestamp format { return time(); } protected function asDateTime($value) // Do not format the time taken out { return $value; } } 4) Delete data using Eloquent ORM: routing: Route::any('orm1', ['uses' => 'CityController@orm1']); Controller: namespace App\Http\Controllers; use App\City; class CityController extends Controller { public function orm1() { // delete by model $city = City::find(9); $bool = $city->delete(); var_dump($bool); //Delete by primary key, return the number of deleted items $delete_rows = City::destroy(8); $delete_rows = City::destroy(6, 7); $delete_rows = City::destroy([6, 7]); var_dump($delete_rows); //Delete by the specified condition, return the number of deleted items $delete_rows = City::where('id', '>', 2)->delete(); var_dump($delete_rows); } } Model: namespace App; use Illuminate\Database\Eloquent\Model; class City extends Model { protected $table = 'city'; // Specify the table name to associate with the model protected $primaryKey = 'id'; // Specify the primary key, the default is id can not be written public $timestamps = false; // Turn off automatic maintenance of timestamps (if changed to true, you need to manually add created_at and updated_at fields in advance, and the time at this time is in datetime format) protected function getDateFormat() // This method can change the datetime type of the created_at and updated_at fields to the timestamp format { return time(); } protected function asDateTime($value) // Do not format the time taken out { return $value; } } 5) Multiple database connections: The .env file is configured as follows: DB_HOST=127.0.0.1 DB_DATABASE=dearedu DB_USERNAME=root DB_PASSWORD=root DB_HOST_DEAREDU_MY=127.0.0.1 DB_PORT_DEAREDU_MY=3306 DB_DATABASE_DEAREDU_MY=dearedu_my DB_USERNAME_DEAREDU_MY=root DB_PASSWORD_DEAREDU_MY=root The config\database.php file is configured as follows: 'mysql' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', 'forge'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', 'forge'), 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', 'strict' => false, ], 'mysql_dearedu_my' => [ 'driver' => 'mysql', 'host' => env('DB_HOST_DEAREDU_MY', 'forge'), 'port' => env('DB_PORT_DEAREDU_MY', '3306'), 'database' => env('DB_DATABASE_DEAREDU_MY', 'forge'), 'username' => env('DB_USERNAME_DEAREDU_MY', 'forge'), 'password' => env('DB_PASSWORD_DEAREDU_MY', 'forge'), 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', 'strict' => false, 'engine' => null, ], The app\Http\Controllers\MemberController.php file is configured as follows: namespace App\Http\Controllers; use App\Member; class MemberController extends Controller { public function index() { $members = Member::getMember(); } } The app\Member.php file is configured as follows: namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\DB; class Member extends Model { public static function getMember() { return DB::select("select mid from cms_member"); } } The app\Http\Controllers\IndexController.php file is configured as follows: namespace App\Http\Controllers; use App\Unit; class IndexController extends Controller { public function index() { $units = Unit::getUnit(); } } The app\Unit.php file is configured as follows: namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\DB; class Unit extends Model { public static function getUnit() { return DB::connection('mysql_dearedu_my')->select("select id from my_config_unit limit 5"); } }
Three ways for Laravel to connect to the database and operate the database
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=324892350&siteId=291194637
Recommended
Ranking