[Laravel] Laravel的基本資料庫操作部分

來源:互聯網
上載者:User
[laravel] laravel的資料庫配置

找到程式目錄結構下.env檔案

配置基本的資料庫連接資訊

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=blog

DB_USERNAME=root

DB_PASSWORD=root

修改完.env檔案需要重啟服務

[laravel] laravel的資料庫入門

控制器中匯入DB資料庫操作類,use DB

使用DB類的靜態方法select來查詢資料庫,DB::select(),參數:sql語句,參數值數組

例如:$user=DB::select("select * from article where id=?",array("1"));

擷取到一個數組,數組中的每一個結果是一個StdClass對象

phpnamespace App\Http\Controllers\Index;use App\Http\Controllers\Controller;use DB;class IndexController extends Controller{    publicfunction index(){        $data=array();        $data['title']="Index控制器";        // 第一種$user=DB::select("select * from article where id=?",array("1"));        foreach ($useras$v) {            echo$v->title;        }        // 第二種$users=DB::table("article")->get();        foreach ($useras$v) {            echo$v->title;        }        return view("index.index",$data);    }}

使用查詢構造器

使用DB::table(),得到查詢構造器對象,參數:表名

調用Builder對象的get()方法,得到數組資料

例如:$users=DB::table("article")->get();

查詢構造器是鏈式調用的,還有其他方法,可以去查看文檔

[laravel] 資料庫的遷移

使用Artisan命令建立遷移,make:migration 名稱 –create 表名

例如:php artisan make:migration create_users_table --create=users

此命令會在database/migrations目錄下面建立一個遷移檔案

開啟產生的遷移檔案,在up方法裡面進列欄位的建立,這裡會用到資料庫的結構構造器Schema

運行遷移命令,使用命令 php artisan migrate,會在資料庫中自動建立表

[laravel] Eloquent模型

使用Eloquent模型為表建立映射模型ORM,使用Artisan命令 make:model 模型名稱

例如:php artisan make:model User

在app目錄下產生一個User.php的模型檔案

以上就介紹了[Laravel] Laravel的基本資料庫操作部分,包括了laravel方面的內容,希望對PHP教程有興趣的朋友有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.