facebook twitter hatena line email

「Php/laravel/laravel5/orm」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(ページの作成:「==laravelのorm== Eloquent ORMをつかう ==モデル自動生成== php artisan make:model Article vi app/Article.php <?php namespace App; use Illuminate\Database\El...」)
 
(モデル自動生成)
行14: 行14:
 
     public $timestamps = true;
 
     public $timestamps = true;
 
  }
 
  }
 +
 +
==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
  
 
==timestamps設定について==
 
==timestamps設定について==

2016年8月3日 (水) 19:25時点における版

laravelのorm

Eloquent ORMをつかう

モデル自動生成

php artisan make:model Article

vi app/Article.php

<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
    protected $primaryKey = 'id';
    protected $table = 'articles';
    public $timestamps = true;
}

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

timestamps設定について

1を設定するとcreated_atとupdated_atに挿入・更新時、自動で日付が入る

| id | created_at          | updated_at          | title | body |
+----+---------------------+---------------------+-------+------+
|  1 | 2016-02-18 22:40:14 | 2016-02-18 22:40:14 | net   |      |

全取得

vi app/Http/Controllers/ArticleController.php

$articles = Article::all();
foreach ($articles as $article) {
    echo $article->id."\n";
    echo $article->title."\n";
}

取得

$article = Article::find(2); // primary keyを引数に入れる // App\Article Objectが返ってくる
echo $article->title;

挿入

$article = new Article();
$article->title = 'net';
$article->save();

更新

$article = Article::find(2);
$article->title = 'it';
$article->save();

削除

$article = Article::find(2);
$article->delete();