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 操作实例的更多相关文章

  1. Laravel使用Eloquent ORM操作数据库

    1.定义模型 <?php namespace App; use Illuminate\Database\Eloquent\Model; class Flight extends Model{ p ...

  2. Laravel Eloquent ORM

    Eloquent ORM 简介 基本用法 集体赋值 插入.更新.删除 软删除 时间戳 查询范围 关系 查询关系 预先加载 插入相关模型 触发父模型时间戳 与数据透视表工作 集合 访问器和调整器 日期调 ...

  3. Laravel 数据库操作 Eloquent ORM

    laravel 操作数据库一般都使用它的Eloquent ORM才操作 建立模型 <?php namespace App; use Illuminate\Database\Eloquent\Mo ...

  4. Laravel 学习笔记之数据库操作——Eloquent ORM

    1. 时间戳 默认情况下在使用ORM操作数据库进行添加.修改数据时, created_at 和 updated_at列会自动存在于数据表中,并显示的是 ‘2017’格式,如果想以 Unix时间戳格式存 ...

  5. [转]Laravel 4之Eloquent ORM

    Laravel 4之Eloquent ORM http://dingjiannan.com/2013/laravel-eloquent/ 定义Eloquent模型 模型通常放在app/models目录 ...

  6. [Laravel] 03 - DB facade, Query builder & Eloquent ORM

    连接数据库 一.Outline 三种操作数据库的方式. 二.Facade(外观)模式 Ref: 解读Laravel,看PHP如何实现Facade? Facade本质上是一个“把工作推给别人做的”的类. ...

  7. laravel使用ORM操作数据库

    laravel使用ORM操作数据库 public function mode(){ //查询所有 $isok=Student::get(); 新增. (1) $isok=Student::create ...

  8. laravel通过Eloquent ORM实现CURD

    //Eloquent ORM public function orm1() { //all(); 返回所有数据: /*$students=Student::all(); dd($students);* ...

  9. laravel Eloquent ORM联合查询出现Class not found,就算在Moel中存在这个类

    今天发现一个坑,在处理Eloquent ORM的联合查询时,一直报错Class 'AdminGroup' not found ,可是我的项目中明明存在这个类,如下 这是我的模型类: 它们的控制器方法: ...

随机推荐

  1. day 11 生成器

    生成器生成器本质就是迭代器,生成器是自己用python代码写的迭代器 将函数变成生成器yield用next 取值一个next,对应一个yield def func(): yield 111 yield ...

  2. 同种类型不同名字的变量在for循环中操作

    InfoViewController * info = [[InfoViewController alloc] init]; HeroViewController * hero = [[HeroVie ...

  3. DMZ原理与应用

    DMZ是英文“demilitarized zone”的缩写,中文名称为“隔离区”,“非军事化区”.它是为了解决安装防火墙后外部网络不能访问内部网络服务器的问题,而设立的一个非安全系统与安全系统之间的缓 ...

  4. 【RabbitMQ】——5种队列(转)

    原文地址:https://blog.csdn.net/u012654963/article/details/76417613 应用RabbitMQ,我们可以根据需求选择5种队列之一. 一.简单队列 P ...

  5. :before与::before的区别

    相同点 都可以用来表示伪类对象,用来设置对象前的内容 :befor和::before写法是等效的  不同点 :befor是Css2的写法,::before是Css3的写法 :before的兼容性要比: ...

  6. Cloud Foundry v2 部署及入门运维

    之前写过一个Guide for Cloud Foundry New Teamer.不过似乎已经有些过时,那会实验室主要是针对的CF v1进行的研究,现在已经全面进入V2时代了.所以更新一下关于Clou ...

  7. mybatis入门--#{}和${}的区别

    我们知道,在mybatis中,sql语句是需要我们自己写的.跟在普通的sql不一样的是,我们在使用mybatis框架的时候,使用的占位符不是 ? 而是 #{} 有时候还会出现这个符号 ${} 这些符号 ...

  8. Activity2.java

    package com.hanqi.text3; import android.app.Activity; import android.os.Bundle; import android.os.Pe ...

  9. Real-time qPCR So Easy?

    Real-time qPCR So Easy? [2016-05-27]       实时荧光定量PCR技术是在定性RCR技术基础上发展起来的核酸定量技术,于1996年由美国Applied biosy ...

  10. ExportGrid Aspose.Cells.dll

    using Aspose.Cells; using Aspose.Words; using System; using System.Collections; using System.Collect ...