Tải bản đầy đủ (.pdf) (51 trang)

Bài giảng Phát triển phần mềm nguồn mở (GV Nguyễn Hữu Thể) Bài 10

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (972.97 KB, 51 trang )

PHÁT TRIỂN PHẦN MỀM NGUỒN MỞ

DATABASE, MIGRATIONS & SEEDING

Nguyễn Hữu Thể


Database
❖ Introduction
❖ Configuration
❖ Read & Write Connections

2


Giới thiệu
− Laravel kết nối tới các database và thực thi các query
với nhiều database back-ends thơng qua sử dụng
• raw SQL,
• fluent query builder,
• Eloquent ORM.

− Hiện tại, Laravel hỗ trợ sẵn 4 database:





MySQL
Postgres
SQLite


SQL Server

3


Cấu hình
− Thư mục config/database.php.
• Trong file này: có thể định nghĩa tất cả các kết nối cơ sở dữ liệu, cũng
như chỉ định connection nào là mặc định.

❖ Cấu hình SQL Server
'sqlsrv' => [
'driver' => 'sqlsrv',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
],

4


Đọc & ghi các kết nối
'mysql' => [
'read' => [
'host' => '192.168.1.1',
],
'write' => [

'host' => '196.168.1.2'
],
'driver'
=> 'mysql',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset'
=> 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix'
=> '',
],
5


Thiết lập database trong file cấu hình chung .env
(Tên_Project/.env)
APP_ENV=local
APP_KEY=base64:SPqqJfE1ADzonR
ot2o5g9J8Ix3iRVHsFOclr0KC1KHI=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=ten_database
DB_USERNAME=root

DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
PUSHER_APP_ID=
PUSHER_KEY=
PUSHER_SECRET=

6


Thực thi lệnh select
namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
public function index()

{
$users = DB::select('select * from users where active = ?', [1]);
return view('user.index', ['users' => $users]);
}

}

Có thể thực thi câu query sử dụng liên kết đặt tên:
$results = DB::select('select * from users where id = :id', ['id' => 1]);
7


Thực thi lệnh select
Syntax

array select(string $query, array $bindings = array())

Parameters

•$query(string) – query to execute in database
•$bindings(array) – values to bind with queries

Returns

array

Description

Run a select statement against the database.


8


Thực thi câu lệnh insert
− Hàm insert nhận câu raw SQL query ở tham số đầu
tiên, và bindings ở tham số thứ hai
DB::insert('insert into users (id, name) values (?, ?)', [1, ‘Tom']);

Syntax

bool insert(string $query, array $bindings = array())

Parameters

•$query(string) – query to execute in database
•$bindings(array) – values to bind with queries

Returns

bool

Description

Run an insert statement against the database.

9


Thực thi câu lệnh update
− Hàm update: update các records đang có trong cơ sở

dữ liệu. Số lượng row ảnh hưởng bởi câu lệnh sẽ
được trả về qua hàm này
$affected = DB::update('update users set votes = 100 where name = ?', ['John']);

Syntax

int update(string $query, array $bindings = array())

Parameters

•$query(string) – query to execute in database
•$bindings(array) – values to bind with queries

Returns

int

Description

Run an update statement against the database.

10


Thực thi câu lệnh delete
− Hàm delete: xoá các records khỏi cơ sở dữ liệu.
Giống như update, số lượng dòng bị xoá sẽ được trả
về
$deleted = DB::delete('delete from users');


Syntax

int delete(string $query, array $bindings = array())

Parameters

•$query(string) – query to execute in database
•$bindings(array) – values to bind with queries

Returns

int

Description

Run a delete statement against the database.

11


Thực thi một câu lệnh chung
− Một vài câu lệnh cơ sở dữ liệu khơng trả về giá trị gì
cả. Với những thao tác kiểu này, có thể sử dụng hàm
statement trong DB facade
DB::statement('drop table users');

12


Database Example

− Table student
Column Name Column Datatype
Id

int(11)

Name

varchar(25)

Extra
Primary key | Auto increment

− We will see how to add, delete, update and retrieve
records from database using Laravel in student table.

13


Database Example - insert
− Step 1 − Execute the below command to create a controller
called StudInsertController
php artisan make:controller StudInsertController

14


Step 2 − Code file app/Http/Controllers/StudInsertController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class StudInsertController extends Controller {
public function insertform(){
return view('stud_create');
}
public function insert(Request $request){
$name = $request->input('stud_name');
DB::insert('insert into student (name) values(?)',[$name]);
echo "Record inserted successfully.
";
echo '<a href = “../insert">Click Here</a> to go back.';
}
}
15


Step 3 − Create a view file resources/views/stud_create.php
<html>
<head>
<title>Student Management | Add</title>
</head>
<body>
<form action="./create" method="post">

<tr>
<td colspan='2'><input type='submit' value="Add student" /></td>
</tr>
</table>
</form>
</body>
</html>
16


Step 4 − Add the following lines in routes\web.php
Route::get('insert','StudInsertController@insertform');
Route::post('create','StudInsertController@insert');

Step 5 − Visit the following URL to insert record in database.

17


Database Example - Update
− Step 1 − Execute the below command to create a controller
called StudViewController.
php artisan make:controller StudUpdateController

18


Step 2 − Code file app/Http/Controllers/ StudUpdateController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class StudUpdateController extends Controller {
public function index(){
$users = DB::select('select * from student');
return view('stud_edit_view',['users'=>$users]);
}
public function show($id) {
$users = DB::select('select * from student where id = ?',[$id]);
return view('stud_update',['users'=>$users]);
}
public function edit(Request $request,$id) {
$name = $request->input('stud_name');
DB::update('update student set name = ? where id = ?',[$name,$id]);
echo "Record updated successfully.
";
echo '<a href = "../edit-records">Click Here</a> to go back.';
}
}


Step 3 − Create a view resources/views/stud_edit_view.blade.php
<html>
<head>
<title>View Student Records</title>
</head>

<body>
<table border = "1">

<tr>
<td>ID</td>
<td>Name</td>
<td>Edit</td>
</tr>
@foreach ($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td><a href = 'edit/{{ $user->id }}'>Edit</a></td>
</tr>
@endforeach
</table>
</body>
</html>


Step 4 − Create another view resources/views/stud_update.php
<html>
<head>
<title>Student Management | Edit</title>
</head>
<body>

</tr>
<tr>
<td colspan = '2'><input type = 'submit' value = "Update student" /></td>
</tr>
</table>
</form>
</body>
</html>


Step 5 − Add the following lines in routes\web.php
Route::get('edit-records','StudUpdateController@index');
Route::get('edit/{id}','StudUpdateController@show');
Route::post('edit/{id}','StudUpdateController@edit');
Step 6 − Visit the following URL to update records in database.



Database Example - Delete
− Step 1 − Execute the below command to create a controller
called StudDeleteController.
php artisan make:controller StudDeleteController


Database Example - Delete
− Step 2 − Code file app/Http/Controllers/StudDeleteController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;

use App\Http\Controllers\Controller;

class StudDeleteController extends Controller {
public function index(){
$users = DB::select('select * from student');
return view('stud_delete_view',['users'=>$users]);
}
public function destroy($id) {
DB::delete('delete from student where id = ?',[$id]);
echo "Record deleted successfully.
";
echo '<a href=“../delete-records">Click Here</a> to go back.';
}
}


×