laravel 5.1 使用Eloquent ORM 操作实例
Laravel 的 Eloquent ORM 提供了更优雅的ActiveRecord 实现来和数据库的互动。 每个数据库表对应一个模型文件。
数据库配置
.env文件(也可以直接修改config/database.php)
DB_HOST=localhost
DB_DATABASE=myblog
DB_USERNAME=root
DB_PASSWORD=root
数据库表:
CREATE TABLE `blog` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`uid` int(11) NOT NULL DEFAULT '0',
`title` varchar(50) NOT NULL DEFAULT '',
`content` text NOT NULL,
`flag` tinyint(2) NOT NULL DEFAULT '1',
`create_time` int(11) NOT NULL DEFAULT '0',
`update_time` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8
一、模型(Model)
在目录下新建 app/Blog.php 文件
<?php namespace App;
use Illuminate\Database\Eloquent\Model; class Blog extends Model{ //指定表名,不指定系统会默认自动对应名称为「类名称的小写复数形态」的数据库表
protected $table = 'blog'; //指定主键,默认就是id
protected $primaryKey = 'id'; //默认情况下,在数据库表里需要有 updated_at 和 created_at 两个字段。如果您不想设定或自动更新这两个字段,则将类里的 $timestamps 属性设为 false即可
public $timestamps = false; }
二、控制器
在目录下新建:app/Http/Controllers/BlogController.php 文件
<?php
namespace App\Http\Controllers; //需要use模型
use App\Blog;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Redirect; class BlogController extends Controller{ public function getIndex() { $list = Blog::all();
return view('blog.index', ['list' => $list]);
} public function getDetail($id) {
$blog = Blog::find($id); return view('blog.detail', ['blog' => $blog]);
} public function getAdd() {
return view('blog.add');
} public function postAdd(Request $request) {
$blog = new Blog;
$blog->title = Input::get('title');
$blog->content = Input::get('content');
$blog->uid = 1;
//保存数据
if ($blog->save()) {
//重定向,需要先导入Illuminate\Support\Facades\Redirect
return Redirect::to('blog');
} else {
return Redirect::back()->withInput()->withErrors('保存失败!');
} } }
二、视图
在目录下新建:resources/views/blog/layout.blade.php 母板视图
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel</title> <link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body> <!--新增按钮-->
<header class="navbar navbar-static-top bs-docs-nav" id="top" role="banner">
<div class="container"> <nav id="bs-navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li>
<a href="{{url('blog/add')}}">新增</a>
</li>
</ul>
</nav>
</div>
</header> @yield('content') <!-- Scripts -->
<script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
<script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>
在目录下新建:resources/views/blog/add.blade.php 视图
@extends('blog.layout')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">新增博客</div>
<div class="panel-body">
<!--错误信息输出-->
@if (count($errors) > 0)
<div class="alert alert-danger">
<strong>输入不正确!</strong> 输入的格式不正确!<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<!--表单-->
<form action="{{ URL('blog/add') }}" method="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="text" name="title" class="form-control" required="required">
<br>
<textarea name="content" rows="10" class="form-control" required="required"></textarea>
<br>
<button class="btn btn-lg btn-info">新增</button>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
在目录下新建:resources/views/blog/index.blade.php 视图
@extends('blog.layout')
@section('content')
@foreach($list as $blog)
<div>
<h1><a href="{{url('blog/detail/'.$blog->id)}}">{{$blog->title}}</a></h1>
<p>{{$blog->content}}</p>
</div>
@endforeach
@endsection
在目录下新建:resources/views/blog/detail.blade.php 视图
@extends('blog.layout')
@section('content')
<div class="jumbotron">
<h1>{{$blog->title}}</h1>
<p>{{$blog->content}}</p>
</div>
@endsection
二、设置路由
\laravel\app\Http\routes.php
<?php /*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/ Route::get('/', function () {
return view('welcome');
}); //对应blog/index
Route::get('blog', 'BlogController@index'); //对应blog里任何方法,注意方法要加get或者post
Route::controller('blog', 'BlogController');
上一篇实例基础:http://www.cnblogs.com/fan-bk/p/8118434.html
例子下载地址: https://files.cnblogs.com/files/fan-bk/laravel.zip
//例子下载后请自行配置数据库。
laravel 5.1 使用Eloquent ORM 操作实例的更多相关文章
- Laravel使用Eloquent ORM操作数据库
1.定义模型 <?php namespace App; use Illuminate\Database\Eloquent\Model; class Flight extends Model{ p ...
- Laravel Eloquent ORM
Eloquent ORM 简介 基本用法 集体赋值 插入.更新.删除 软删除 时间戳 查询范围 关系 查询关系 预先加载 插入相关模型 触发父模型时间戳 与数据透视表工作 集合 访问器和调整器 日期调 ...
- Laravel 数据库操作 Eloquent ORM
laravel 操作数据库一般都使用它的Eloquent ORM才操作 建立模型 <?php namespace App; use Illuminate\Database\Eloquent\Mo ...
- Laravel 学习笔记之数据库操作——Eloquent ORM
1. 时间戳 默认情况下在使用ORM操作数据库进行添加.修改数据时, created_at 和 updated_at列会自动存在于数据表中,并显示的是 ‘2017’格式,如果想以 Unix时间戳格式存 ...
- [转]Laravel 4之Eloquent ORM
Laravel 4之Eloquent ORM http://dingjiannan.com/2013/laravel-eloquent/ 定义Eloquent模型 模型通常放在app/models目录 ...
- [Laravel] 03 - DB facade, Query builder & Eloquent ORM
连接数据库 一.Outline 三种操作数据库的方式. 二.Facade(外观)模式 Ref: 解读Laravel,看PHP如何实现Facade? Facade本质上是一个“把工作推给别人做的”的类. ...
- laravel使用ORM操作数据库
laravel使用ORM操作数据库 public function mode(){ //查询所有 $isok=Student::get(); 新增. (1) $isok=Student::create ...
- laravel通过Eloquent ORM实现CURD
//Eloquent ORM public function orm1() { //all(); 返回所有数据: /*$students=Student::all(); dd($students);* ...
- laravel Eloquent ORM联合查询出现Class not found,就算在Moel中存在这个类
今天发现一个坑,在处理Eloquent ORM的联合查询时,一直报错Class 'AdminGroup' not found ,可是我的项目中明明存在这个类,如下 这是我的模型类: 它们的控制器方法: ...
随机推荐
- swift - 本地通知2 - 啰嗦版
1. import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var windo ...
- dUMP:A new value is to be assigned to the field "<L_BOX>"
DUMP: A new value is to be assigned to the field "<L_BOX>", although this field is e ...
- clickableSpan实现textView文字部分点击有响应
先定义一个clickableSpan的子类 class MyClickText extends ClickableSpan{ private Context context; public MyCli ...
- CSS-解决苹果点击高亮、安卓select灰色背景(select下拉框在IOS中背景变黑、出现阴影问题)
1.在苹果手机上,用点击事件后会出现一个高亮的阴影: 面对click事件的阴影,解决办法: *{ -webkit-tap-highlight-color: rgba(0,0,0,0); -webkit ...
- Django ORM那些相关操作zi
Django ORM那些相关操作 一般操作 看专业的官网文档,做专业的程序员! 必知必会13条 <1> all(): 查询所有结果 <2> filter(**kwargs) ...
- PAT 1011 A+B和C (15)(C++&JAVA&Python)
1011 A+B和C (15)(15 分) 给定区间[-2^31^, 2^31^]内的3个整数A.B和C,请判断A+B是否大于C. 输入格式: 输入第1行给出正整数T(<=10),是测试用例的个 ...
- asp.net读取xml接口
//发送获取xml请求 public static string SentRequest(String url) { HttpWebRequest req = WebRequest.CreateHtt ...
- 简单的node 服务端 响应get,返回json数据;
原文:http://blog.csdn.net/xn_28/article/details/50837019 const http = require('http'); const hostname ...
- python 计时程序运行时间
import time time_start=time.time() time_end=time.time() print('totally cost',time_end-time_start)
- php mysql 丢失更新
php mysql 丢失更新问题,搜索整个互联网,很少有讲到,也许和php程序员出身一般都是非科班出身有关系吧. 另外php程序一般都是简单数据,很少有并发一致性问题,所以大家都没有谁专门提出这个问题 ...