CI3中实现Laravel的Eloquent ORM操作数据库

前言:PHP 版本要求 >= 5.4,这是 Eloquent 的最低要求。

  1. composer.json 里面添加 "illuminate/database": "*" 依赖,并且执行
    composer update
  2. application/helpers 里添加一个 helper, 名为 eloquent_helper.php,
    内容如下代码片段①。
  3. config/autoload.php 中的 $autoload['helper'] 中添加 eloquent,效果如下:$autoload['helper'] = array('view', 'eloquent');
  4. config/config.php 中的 $config['composer_autoload'] 配置修改为:$config['composer_autoload'] = './vendor/autoload.php';
  5. application/config/database.php 数据库连接配置正确。

代码片段①

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use Illuminate\Database\Capsule\Manager as Capsule;
// require the ci database config
require_once APPPATH.'config/database.php';
// Eloquent ORM
$capsule = new Capsule;
$capsule->addConnection(
    array(
        'driver'    => 'mysql',
        'host'      => $db['default']['hostname'],
        'database'  => $db['default']['database'],
        'username'  => $db['default']['username'],
        'password'  => $db['default']['password'],
        'charset'   => $db['default']['char_set'],
        'collation' => $db['default']['dbcollat'],
        'prefix'    => $db['default']['dbprefix']
    )
);
//boot Eloquent
$capsule->bootEloquent();

一个Controller和Model示例:

application/models/Typecho_contents.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use Illuminate\Database\Eloquent\Model as Eloquent;

class Typecho_contents extends Eloquent
{
    protected $table = 'typecho_contents';
    protected $primaryKey = 'cid';
    public $timestamps = false;
}

application/controllers/Blog.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Blog extends CI_Controller {

    public function index()
    {
        $this->load->model('typecho_contents');
        $example = $this->typecho_contents->findOrFail(1);
        dd($example->toArray(), Typecho_contents::all());
    }
}

标签: 无

发表评论: