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 ,可是我的项目中明明存在这个类,如下 这是我的模型类: 它们的控制器方法: ...
随机推荐
- Python中新式类 经典类的区别(即类是否继承object)
首先什么是新式类 经典类呢: #新式类是指继承object的类 class A(obect): ........... #经典类是指没有继承object的类 class A: ........... ...
- gearman中worker常驻后台,导致MySQL server has gone away
产生这个原因主要有如下几点: 1.mysql服务宕机了 2.长时间没有操作,超过了wait_timeout的设置,mysql自动断开 3.mysql请求链接被主动kill 4.发送的请求或返回结果过大 ...
- Java并发集合(三)-ConcurrentHashMap分析和使用
1 http://ifeve.com/hashmap-concurrenthashmap-%E7%9B%B8%E4%BF%A1%E7%9C%8B%E5%AE%8C%E8%BF%99%E7%AF%87% ...
- Linux硬件相关
1)查看设备号/厂商号 http://blog.csdn.net/styshoo/article/details/51203881 二.硬件厂商 1)瑞传科技股份有限公司 https://www. ...
- 22.Mysql磁盘I/O
22.磁盘I/O问题磁盘IO是数据库性能瓶颈,一般优化是通过减少或延缓磁盘读写来减轻磁盘IO的压力及其对性能的影响.增强磁盘读写性能和吞吐量也是重要的优化手段. 22.1 使用磁盘阵列 RAID(Re ...
- Task 和 ThreadPool
在C#中 TASK 和 ThreadPool 都可以完成多任务并行的工作.但是 TASK实际上是微软定义好的,基于 ThreadPool 的一个类.这里面微软做了很多优化工作. Task Parall ...
- layer.confirm在ASP.NET控件onclick上面的应用方法
有些时候,你可能要修改控件的事件,元素本身.等,这个时候如何操作呢?下面提供一个思路: <asp:LinkButton Visible="false" ID="sh ...
- Spring Boot 2.0(二):Spring Boot 开源软件都有哪些?(转)
2016年 Spring Boot 还没有被广泛使用,在网上查找相关开源软件的时候没有发现几个,到了现在经过2年的发展,很多互联网公司已经将 Spring Boot 搬上了生产,而使用 Spring ...
- Loadrunner使用键盘快捷键
---------Loadrunner使用键盘快捷键------------ alt+f8 比较当前快照(仅限于 Web Vuser) alt+ins 新建步骤 ctrl+a 全选 ctrl+c 复制 ...
- MacDev.GarbageCollectionIsDeprecated-WhenXcodeCompileMacAppProject
Garbage Collection is not supported 当Xcode编译Mac OSX App时报错:"Garbage Collection is not supported ...