作为程序员一定要保持良好的睡眠,才能好编程

laravel 开发评论模块

发布时间:2020-02-01


1、创建表

使用migration 创建表

G:\phpstudy\WWW\laravel_base>php artisan make:migration create_comments_table
Created Migration: 2020_01_19_223557_create_comments_table


databases/CreateCommentsTable.php


<?php

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

class CreateCommentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('post_id')->default(0);
            $table->integer('user_id')->default(0);
            $table->text('content');
            $table->integer('status')->default(1)->comment('状态表 1 显示 0 不显示');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('comments');
    }
}


然后执行  php artisan migrate


image.png


看到表创建完成


2、创建模型

使用 php artisan 创建模型

G:\phpstudy\WWW\laravel_base>php artisan make:model Comment
Model created successfully.

image.png


常见的关联模型有: 1对1  1对多  1对多的反向


Comment.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

/**
 * 评论模型
 * Class Comment
 * @package App
 */
class Comment extends Model
{

    public function post(){
        return $this->belongsTo(Post::class,'id','post_id');
    }


}



Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

/**
 * 新闻模型
 * Class Post
 * @package App
 */
class Post extends Model
{
    //

    public function comments()
    {
        return $this->hasMany(Comment::class, 'comment_id', 'id');
        return $this->hasMany(Comment::class, 'comment_id', 'id')->orderby(('id','desc'); //还可以做数据的排序  或者select 字段的选择
    }
}




3、创建控制器


模型关联保存


//这样保存 传递进来的是什么?  是一个post的对象

$post->comments()->save() 


image.png

关联模型保存数据



 image.png


comments 这个参数名是在模型中关联模型的函数名。

获取新闻的关联数量



4、写路由

Route::post('posts/{id}/comment','\App\Http\Controllers\PostsController@comment');



5、使用示例代码

<?php


$post = Posts::find(1);

$comment =  new Comment();
$comment->user_id = 0;
$comment->content = request('content');

$post->comments()->save($comment);


保存一个评论,这个时候,可以根据 $post 模型去获取到属性,自动去谁知评论里面的关联数据。


save()   这个方法传递参数必须是 model 模型

create() 这个方法里可以传递 数组




Laravel预加载方式:

Laravel 预加载方式

image.png

以上的两种方式都是预加载的。


必须使用预加载,不要在view层 进行业务逻辑的判断。



还有一种方式就是 使用  $books->author  这不是预加载。







Laravel模型故关联

image.png

image.pngimage.png