laravel 5.1 使用Eloquent ORM 操作实例

时间:2022-12-10 09:42:14

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

//例子下载后请自行配置数据库。