octobercms数据库使用

运行原始SQL查询

//运行select查询
$users = Db::select('select * from users where active = ?', [1]);
传递给该select方法的第一个参数是原始SQL查询,而第二个参数是需要绑定到查询的任何参数绑定。通常,这些是where子句约束的值。参数绑定提供了针对SQL注入的保护。

该select方法将始终返回一个array结果。数组中的每个结果将是一个PHP stdClass对象,允许您访问结果的值:
foreach ($users as $user) {
    echo $user->name;
}

//使用命名绑定
$results = Db::select('select * from users where id = :id', ['id' => 1]);

//运行一个insert语句
要执行一个insert语句,你可以使用insert在Db立面上的方法。像这样select,这个方法将原始SQL查询作为第一个参数,绑定作为第二个参数:
Db::insert('insert into users (id, name) values (?, ?)', [1, 'Joe']);

//运行更新语句
该update方法应用于更新数据库中的现有记录。该语句受影响的行数将由方法返回:
$affected = Db::update('update users set votes = 100 where name = ?', ['John']);

//运行delete语句
该delete方法应用于从数据库中删除记录。喜欢update,将返回删除的行数:
$deleted = Db::delete('delete from users');

//运行一般声明
某些数据库语句不应返回任何值。对于这些类型的操作,您可以使用立面上的statement方法Db
Db::statement('drop table users');

//多个数据库连接
当使用多个连接时,您可以通过立面上的connection方法访问每个连接Db。在name传递给connection方法应该对应于您列出的其中一个连接config/database.php组态文件中
$users = Db::connection('foo')->select(...);
$pdo = Db::connection()->getPdo();

//数据库事务
Db::transaction(function () {
    Db::table('users')->update(['votes' => 1]);

    Db::table('posts')->delete();
});

//手动使用交易
如果您想手动开始事务并完全控制回滚和提交,您可以使用立面上的beginTransaction方法Db:
Db::beginTransaction();
您可以通过以下rollBack方法回滚事务:
Db::rollBack();
最后,您可以通过以下commit方法提交事务:
Db::commit();

//数据库事件
如果要接收应用程序执行的每个SQL查询,可以使用该listen方法。此方法对于记录查询或调试很有用。
Db::listen(function($sql, $bindings, $time) {
    //
});

//查询记录
启用查询日志记录时,将记录所有已为当前请求运行的查询的内存。调用该enableQueryLog方法启用此功能
Db::connection()->enableQueryLog();
要获取执行查询的数组,可以使用以下getQueryLog方法:
$queries = Db::getQueryLog();
然而,在某些情况下,例如当插入大量行时,这可能导致应用程序使用多余的内存。要禁用日志,您可以使用以下disableQueryLog方法:
Db::connection()->disableQueryLog();

检索结果

//从表中检索所有行--get来看一下表中的所有记录
$users = Db::table('users')->get();
//通过访问列作为对象的属性来访问每列的值:
foreach ($users as $user) {
    echo $user->name;
}
//从表中检索单个行/列
$user = Db::table('users')->where('name', 'John')->first();
echo $user->name;
//如果您甚至不需要整行,您可以使用该value方法从记录中提取单个值。此方法将直接返回列的值:
$email = Db::table('users')->where('name', 'John')->value('email');
//分块结果从一张桌子
Db::table('users')->chunk(100, function($users) {
    foreach ($users as $user) {
        //
    }
});
//您可以通过以下方式返回false来阻止进一步处理的块Closure:
Db::table('users')->chunk(100, function($users) {
    // Process the records...

    return false;
});
//检索列值列表
//如果要检索包含单列值的数组,则可以使用该lists方法
$titles = Db::table('roles')->lists('title');

foreach ($titles as $title) {
    echo $title;
}

//您还可以为返回的数组指定自定义键列:
$roles = Db::table('roles')->lists('title', 'name');

foreach ($roles as $name => $title) {
    echo $title;
}

//骨料
$users = Db::table('users')->count();
$price = Db::table('orders')->max('price');
$price = Db::table('orders')
    ->where('is_finalized', 1)
    ->avg('price');

//选择
$users = Db::table('users')->select('name', 'email as user_email')->get();
//该distinct方法允许您强制查询返回不同的结果:
$users = Db::table('users')->distinct()->get();

$query = Db::table('users')->select('name');
$users = $query->addSelect('age')->get();
//原始表达式
$users = Db::table('users')
    ->select(Db::raw('count(*) as user_count, status'))
    ->where('status', '<>', 1)
    ->groupBy('status')
    ->get();
//加盟
$users = Db::table('users')
    ->join('contacts', 'users.id', '=', 'contacts.user_id')
    ->join('orders', 'users.id', '=', 'orders.user_id')
    ->select('users.*', 'contacts.phone', 'orders.price')
    ->get();
$users = Db::table('users')
    ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
    ->get();
Db::table('users')
    ->join('contacts', function ($join) {
        $join->on('users.id', '=', 'contacts.user_id')->orOn(...);
    })
    ->get();
Db::table('users')
    ->join('contacts', function ($join) {
        $join->on('users.id', '=', 'contacts.user_id')
            ->where('contacts.user_id', '>', 5);
    })
    ->get();
//where子句
$users = Db::table('users')->where('votes', '=', 100)->get();
$users = Db::table('users')->where('votes', 100)->get();
$users = Db::table('users')
    ->where('votes', '>=', 100)
    ->get();

$users = Db::table('users')
    ->where('votes', '<>', 100)
    ->get();

$users = Db::table('users')
    ->where('name', 'like', 'T%')
    ->get();
//“或”声明
$users = Db::table('users')
    ->where('votes', '>', 100)
    ->orWhere('name', 'John')
    ->get();
//“之间”之间的陈述
$users = Db::table('users')
    ->whereBetween('votes', [1, 100])->get();
$users = Db::table('users')
    ->whereNotBetween('votes', [1, 100])
    ->get();
//“在哪里”声明
$users = Db::table('users')
    ->whereIn('id', [1, 2, 3])
    ->get();
$users = Db::table('users')
    ->whereNotIn('id', [1, 2, 3])
    ->get();
//“null”语句
$users = Db::table('users')
    ->whereNull('updated_at')
    ->get();
$users = Db::table('users')
    ->whereNotNull('updated_at')
    ->get();

//排序
$users = Db::table('users')
    ->orderBy('name', 'desc')
    ->get();
//分组
$users = Db::table('users')
    ->groupBy('account_id')
    ->having('account_id', '>', 100)
    ->get();
//该havingRaw方法可用于将原始字符串设置为having子句的值。例如,我们可以找到销售额超过$ 2,500的所有部门:
$users = Db::table('orders')
    ->select('department', Db::raw('SUM(price) as total_sales'))
    ->groupBy('department')
    ->havingRaw('SUM(price) > 2500')
    ->get();
//限制和抵消
//要限制从查询返回的结果数,或者在查询(OFFSET)中跳过给定数量的结果,可以使用skip和take方法:
$users = Db::table('users')->skip(10)->take(5)->get();

//插入
Db::table('users')->insert(
    ['email' => 'john@example.com', 'votes' => 0]
);
Db::table('users')->insert([
    ['email' => 'taylor@example.com', 'votes' => 0],
    ['email' => 'dayle@example.com', 'votes' => 0]
]);
//自动递增ID
$id = Db::table('users')->insertGetId(
    ['email' => 'john@example.com', 'votes' => 0]
);
//更新
Db::table('users')
    ->where('id', 1)
    ->update(['votes' => 1]);
//递增/递减
Db::table('users')->increment('votes');
Db::table('users')->increment('votes', 5);
Db::table('users')->decrement('votes');
Db::table('users')->decrement('votes', 5);
Db::table('users')->increment('votes', 1, ['name' => 'John']);
//删除
Db::table('users')->delete();
Db::table('users')->where('votes', '<', 100)->delete();
Db::table('users')->truncate();
//悲观锁定
Db::table('users')->where('votes', '>', 100)->sharedLock()->get();
Db::table('users')->where('votes', '>', 100)->lockForUpdate()->get();

//缓存查询
//持久缓存
$users = Db::table('users')->remember(10)->get();
//内存缓存
Db::table('users')->get(); // Result from database
Db::table('users')->get(); // Result from database
Model::all(); // Result from database
Model::all(); // Result from in-memory cache
//您可以使用enableDuplicateCache或disableDuplicateCache方法启用或禁用重复缓存
Db::table('users')->enableDuplicateCache()->get();
//如果查询存储在缓存中,则当使用insert,update,delete或truncate语句时,它将自动被清除。但是您可以使用该flushDuplicateCache方法手动清除缓存
Db::table('users')->enableDuplicateCache()->get();

models:

//介绍
plugins/
  acme/
    blog/
      models/
        user/             <=== Model config directory
          columns.yaml    <=== Model config files
          fields.yaml     <==^
        User.php          <=== Model class
      Plugin.php
//定义模型
namespace Acme\Blog\Models;
use Model;
class Post extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'acme_blog_posts';
}
//支持的属性
class User extends Model
{
    protected $primaryKey = 'id';
    public $exists = false;
    protected $dates = ['last_seen_at'];
    public $timestamps = true;
    protected $jsonable = ['permissions'];
    protected $guarded = ['*'];
}
//首要的关键
class Post extends Model
{
    /**
     * The primary key for the model.
     *
     * @var string
     */
    protected $primaryKey = 'id';
}
//时间戳
class Post extends Model
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;
}
//如果您需要自定义时间戳的格式,请设置$dateFormat模型上的属性。此属性确定日期属性如何存储在数据库中,以及当模型序列化为数组或JSON时的格式:
class Post extends Model
{
    /**
     * The storage format of the model's date columns.
     *
     * @var string
     */
    protected $dateFormat = 'U';
}
//值存储为JSON
class Post extends Model
{
    /**
     * @var array Attribute names to encode and decode using JSON.
     */
    protected $jsonable = ['data'];
}
//访问列值
foreach ($flights as $flight) {
    echo $flight->name;
}
//添加附加约束
$flights = Flight::where('active', 1)
    ->orderBy('name', 'desc')
    ->take(10)
    ->get();
//集合
foreach ($flights as $flight) {
    echo $flight->name;
}
//分块结果
Flight::chunk(200, function ($flights) {
    foreach ($flights as $flight) {
        //
    }
});
//检索单个模型
// Retrieve a model by its primary key
$flight = Flight::find(1);

// Retrieve the first model matching the query constraints
$flight = Flight::where('active', 1)->first();

//找不到例外
$model = Flight::findOrFail(1);
$model = Flight::where('legs', '>', 100)->firstOrFail();

Route::get('/api/flights/{id}', function ($id) {
    return Flight::findOrFail($id);
});

//检索聚合
$count = Flight::where('active', 1)->count();
$max = Flight::where('active', 1)->max('price');

//基本插入
$flight = new Flight;
$flight->name = 'Sydney to Canberra';
$flight->save();

//基本更新
$flight = Flight::find(1);
$flight->name = 'Darwin to Adelaide';
$flight->save();
//还可以针对与给定查询匹配的任意数量的模型执行更新。在这个例子中,所有的航班active,有一个destination的San Diego将被标记为延迟:
Flight::where('is_active', true)
    ->where('destination', 'Perth')
    ->update(['delayed' => true]);
//质量分配
class Flight extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name'];
}
//一旦我们赋予了属性质量分配,我们可以使用该create方法在数据库中插入新的记录。该create方法返回保存的模型实例:
$flight = Flight::create(['name' => 'Flight 10']);

//其他创作方法
$flight = Flight::make(['name' => 'Flight 10']);

// Functionally the same as...
$flight = new Flight;
$flight->fill(['name' => 'Flight 10']);

// Retrieve the flight by the attributes, otherwise create it
$flight = Flight::firstOrCreate(['name' => 'Flight 10']);

// Retrieve the flight by the attributes, or instantiate a new instance
$flight = Flight::firstOrNew(['name' => 'Flight 10']);

//删除模型
$flight = Flight::find(1);
$flight->delete();

//按键删除现有的模型
Flight::destroy(1);
Flight::destroy([1, 2, 3]);
Flight::destroy(1, 2, 3);

//通过查询删除模型
$deletedRows = Flight::where('active', 0)->delete();

//查询范围
class User extends Model
{
    /**
     * Scope a query to only include popular users.
     */
    public function scopePopular($query)
    {
        return $query->where('votes', '>', 100);
    }

    /**
     * Scope a query to only include active users.
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', 1);
    }
}

//利用查询范围
$users = User::popular()->active()->orderBy('created_at')->get();

//动态范围
class User extends Model
{
    /**
     * Scope a query to only include users of a given type.
     */
    public function scopeApplyType($query, $type)
    {
        return $query->where('type', $type);
    }
}

//现在您可以在调用范围时传递参数:
$users = User::applyType('admin')->get();

 

posted @ 2017-08-21 18:21  wjd0215  阅读(797)  评论(0编辑  收藏  举报