facebook twitter hatena line google mixi email

Php/laravel/laravel5/db

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

mysql設定

vi config/database.php

       'mysql' => [
           'driver'    => 'mysql',
           'host'      => env('DB_HOST', 'localhost'),
           'database'  => env('DB_DATABASE', 'forge'),
           'username'  => env('DB_USERNAME', 'forge'),
           'password'  => env('DB_PASSWORD', ),
           'charset'   => 'utf8',
           'collation' => 'utf8_unicode_ci',
           'prefix'    => ,
           'strict'    => false,
           'engine'    => null,
       ],

table作成

CREATE TABLE `articles` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `created_at` datetime NOT NULL,
 `updated_at` datetime NOT NULL,
 `title` varchar(63) DEFAULT NULL,
 `body` text NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

取得

use DB;
class ArticleController extends Controller
{
   public function index()
   {
       $articles = DB::select('select * from articles where id = ?', [1]);
   }
}
Array(
  [0] => stdClass Object(
    [id] => 1
    [title] => net
))

挿入

DB::insert('insert into articles (id, title) values (?, ?)', [1, 'net']);

更新

$affected = DB::update('update articles set title = ?', ['it']);

hit時は1, hitがない時は0が戻る

削除

$deleted = DB::delete('delete from articles');

hit時は1, hitがない時は0が戻る

トランザクション

DB::beginTransaction();
DB::rollBack();
DB::commit();

502 Bad Gatewayなどとなる場合は以下が追加されてるか確認する

use DB;

接続エラー

Access denied for user 'homestead'@'localhost' 

以下も変更すれば良い

$ vi .env
DB_HOST=127.0.0.1
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

参考

公式ページ:http://readouble.com/laravel/5/1/ja/database.html