basephp/database

BasePHP 包:数据库

v1.0.1 2018-08-27 20:22 UTC

This package is auto-updated.

Last update: 2024-08-29 04:43:10 UTC


README

注意: 此存储库需要使用 BasePHP 框架。如果您想了解更多关于框架的信息,请访问 BasePHP

BasePHP 组件 - 数据库

BasePHP 的数据库和查询构建器。

快速链接

安装

(1) 在您的 .env 文件中添加敏感信息

DB_USER=admin
DB_PASS=password
DB_HOST=127.0.0.1
DB_NAME=database
DB_PORT=3306
DB_DRIVER=MySQLi

(2) 如果您没有 /config/db.php,则从本存储库复制 db.example.php 并重命名它。

示例

use \Base\Support\Facades\DB;

结果

// get a single user from the database
$user = DB::table('users')->where('id',912864)->first();

// get all users in the database, order the results
$users = DB::table('users')->order('id ASC')->get();

// get all users that have gmail email address (writing custom SQL)
$users = DB::table('users')->where('email LIKE "%gmail.com" ')->get();

// count how many users are enabled
$enabledUsers = DB::table('users')->where(['status'=>'enabled'])->count();

// get most recent 10 enabled users
$users = DB::table('users')
            ->select(['id','name'])
            ->where(['status'=>'enabled'])
            ->limit(10)
            ->order('id DESC')
            ->get();

// get all the cities that have over 1,000,000 population
$cities = DB::table('postal_codes')
            ->group('city')
            ->having('population > 1000000')
            ->get();

// get the average price of all ebooks from the products table
$avgPrice = DB::table('products')->where('category','ebooks')->avg('price');

更新项目

// change user's name
DB::table('users')
    ->where('id',912864)
    ->update([
        'name' => 'John Smith'
    ]);

// increase this users "page view" count
DB::table('users')->where('id',9983287)->increment('page_view',1);

插入项目

// add a new user to the table, and return the new ID
$newUserId =  DB::table('users')
                ->insert([
                    'name' => 'John Smith',
                    'email' => 'jsmith@email.com'
                ]);

删除项目

// delete a user by id
DB::table('users')
    ->where('id',912864)
    ->delete();

// delete all users with deleted = 1
DB::table('users')
    ->where(['deleted' => 1])
    ->delete();

原始 SQL

// Writing a RAW SQL query to get 10 products from the database.
$products = DB::query("SELECT * FROM products WHERE status = 'enabled' LIMIT 10");
foreach($products as $product)
{
    // display products here
}

// get a single products
$product = DB::query("SELECT * FROM products WHERE id = '$productId'")->first();

// writing an update query
DB::query("UPDATE products SET price = 61.41 WHERE id = '$id' ");

// writing raw queries (without the query builder)
$newUserId = DB::query("INSERT INTO users WHERE name = 'John Smith', email = 'jsmith@email.com' ");

查询构建器

这些方法可以堆叠

注意:对于每个新的查询,首先使用 table() 方法。

执行查询

这些方法执行“读取”查询并返回数据库结果

这些方法执行“写入”查询

编写原始查询

注意:原始查询将结果返回到 Collection,除非您正在“写入”数据库。

注意:使用 INSERT 的查询将自动返回 insert_id

实用方法

注意:所有传递给查询方法(非自定义 SQL)的值都会自动通过 escape() 运行。

数据库支持

目前仅支持 MySQL 连接