美文网首页
Laravel框架 之 懒加载

Laravel框架 之 懒加载

作者: 诺之林 | 来源:发表于2018-07-20 16:31 被阅读257次

本文的示例代码参考eloquent-association

目录

开始

docker run --name eloquent-association -p 3306:3306 -e MYSQL_ROOT_PASSWORD=secret -d mysql:5.7.17

docker exec -i eloquent-association mysql -uroot -psecret  <<< "CREATE DATABASE IF NOT EXISTS homestead DEFAULT CHARSET utf8 COLLATE utf8_general_ci;"
composer create-project laravel/laravel eloquent-association && cd eloquent-association

sed -i "" "s/DB_USERNAME=homestead/DB_USERNAME=root/g" .env

Model

Post

php artisan make:model Models/Post -m
vim app/Models/Post.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = ['title'];

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}
vim database/migrations/*create_posts_table.php
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title')->index();
        });
    }

    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

Comment

php artisan make:model Models/Comment -m
vim app/Models/Comment.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    protected $fillable = ['content'];

    public function post()
    {
        return $this->belongsTo(Post::class);
    }
}
vim database/migrations/*create_comments_table.php
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCommentsTable extends Migration
{
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->text('content');
            $table->integer('post_id')->unsigned()->default(0)->index();
        });
    }

    public function down()
    {
        Schema::dropIfExists('comments');
    }
}

php artisan migrate

Seed

php artisan make:seed PostsTableSeeder
vim database/seeds/PostsTableSeeder.php
<?php

use Illuminate\Database\Seeder;
use App\Models\Post;

class PostsTableSeeder extends Seeder
{
    public function run()
    {
        $post = [
            'title' => 'post1',
        ];
        Post::insert($post);
    }
}
php artisan make:seed CommentsTableSeeder
vim database/seeds/CommentsTableSeeder.php
<?php

use Illuminate\Database\Seeder;
use App\Models\Comment;

class CommentsTableSeeder extends Seeder
{
    public function run()
    {
        $comment = [
            'post_id' => 1,
            'content' => 'post1-comment1',
        ];
        Comment::insert($comment);
        $comment = [
            'post_id' => 1,
            'content' => 'post1-comment2',
        ];
        Comment::insert($comment);
    }
}
vim database/seeds/DatabaseSeeder.php
<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        $this->call(PostsTableSeeder::class);
        $this->call(CommentsTableSeeder::class);
    }
}

php artisan db:seed

Controller

php artisan make:controller PostsController
vim app/Http/Controllers/PostsController.php
<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class PostsController extends Controller
{
    public function show(Request $request, Post $post)
    {
        return $post;
    }

    public function comments(Request $request, Post $post)
    {
        return $post->comments;
    }
}

Route

vim routes/web.php
<?php

Route::get('/', function () {
    return view('welcome');
});

Route::get('/posts/{post}', 'PostsController@show');
Route::get('/posts/{post}/comments', 'PostsController@comments');

测试

vim app/Providers/AppServiceProvider.php
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use DB;
use Log;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        DB::listen(function($query) {
            Log::info(
                $query->sql,
                $query->bindings,
                $query->time
            );
        });
    }
}
php artisan serve
# Laravel development server started: <http://127.0.0.1:8000>
curl -X GET http://127.0.0.1:8000/posts/1 | json
{
  "id": 1,
  "title": "post1"
}
cat storage/logs/laravel.log
[2018-07-20 08:22:48] local.INFO: select * from `posts` where `id` = ? limit 1 ["1"]
curl -X GET http://127.0.0.1:8000/posts/1/comments | json
[
  {
    "id": 1,
    "content": "post1-comment1",
    "post_id": 1
  },
  {
    "id": 2,
    "content": "post1-comment2",
    "post_id": 1
  }
]
cat storage/logs/laravel.log
[2018-07-20 08:22:48] local.INFO: select * from `posts` where `id` = ? limit 1 ["1"]
[2018-07-20 08:23:23] local.INFO: select * from `posts` where `id` = ? limit 1 ["1"]
[2018-07-20 08:23:23] local.INFO: select * from `comments` where `comments`.`post_id` = ? and `comments`.`post_id` is not null [1]

Reference

相关文章

  • Laravel框架 之 懒加载

    本文的示例代码参考eloquent-association 目录 开始 ModelPostCommentSeed ...

  • laravel之一二

    第一天:开始学习laravel 框架 首先 了解 laravel的运行流程 第一步:包含自动加载文件 requir...

  • 吃饱了才能撑着

    第一天:开始学习laravel 框架 首先 了解 laravel的运行流程 第一步:包含自动加载文件 requir...

  • laravel源码学习(1)-从自加载开始

    laravel源码学习(1)-从自加载开始 前言 工作一年多,框架用过symfony,thinkphp,larav...

  • AVPlayer播放远程音频

    导入框架 播放器属性和懒加载 点击屏幕开始播放

  • laravel初接触

    laravel中文文档 一、本地安装laravel框架 通过composer安装laravel框架: 二、执行ar...

  • PHP Laravel 学习之加载前端框架Bootstrap

    写在前面:本文通过学习Lraravel china课程中使用端框架Bootstrap的总结。分割线 Bootstr...

  • Then语法的使用

    Then是一个开源的swift框架,使懒加载的写法更美观和方便,详情见 github地址 使用: 懒加载的写法一般...

  • 知识点汇总

    Laravel框架关键技术 熟悉SOLID原则 了解部分设计模式 熟悉Composer的自动加载原理和造轮子规范 ...

  • TP框架和Laravel框架的区别是什么?

    TP框架: Laravel框架: TP框架和Laravel框架的区别: 1、提交数据的方式 2、路由 3、渲染模版...

网友评论

      本文标题:Laravel框架 之 懒加载

      本文链接:https://www.haomeiwen.com/subject/gtjqmftx.html