溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

laravel框架中怎么操作數(shù)據(jù)庫

發(fā)布時(shí)間:2021-07-19 14:47:29 來源:億速云 閱讀:132 作者:Leah 欄目:開發(fā)技術(shù)

本篇文章給大家分享的是有關(guān)laravel框架中怎么操作數(shù)據(jù)庫,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

laravel 數(shù)據(jù)庫配置

數(shù)據(jù)庫配置文件為項(xiàng)目根目錄下的config/database.php

//默認(rèn)數(shù)據(jù)庫為mysql
'default' => env('DB_CONNECTION', 'mysql'), 
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],

發(fā)現(xiàn)都在調(diào)用env函數(shù),找到env文件,即根目錄下的.env文件,

打開修改配置參數(shù)

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

修改為本地的數(shù)據(jù)庫信息:

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=123456

laravel 操作數(shù)據(jù)庫

建立student控制器,控制器代碼

namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
class StudentController extends Controller
{
  //添加
  public function addstudent(){
    $student = DB::insert('insert into student(name,age,gender) values(?,?,?)',['張三',12,2]);
    var_dump($student);//成功返回bloo值true
  }
  //獲取
  public function getall(){
//    $student = DB::select('select * from student');
    $student = DB::select('select * from student where id>?',[1]);
    return $student;//數(shù)組
  }
  //修改
  public function updstudent(){
    $student = DB::update('update student set age= ? where name=?',[10,'張三']);
    var_dump($student);//成功返回bloo值true
  }
  //修改
  public function delstudent(){
    $student = DB::delete('delete from student where id=?',[10]);
    var_dump($student);
  }
}

注意 laravel中return true會(huì)報(bào)錯(cuò):

(1/1) UnexpectedValueException
The Response content must be a string or object implementing __toString(), "boolean" given.

以上就是laravel框架中怎么操作數(shù)據(jù)庫,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI