php评论模块,laravel 开发评论模块

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

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

7d1774e129eef19e874b2260f19d2040.png

看到表创建完成

2、创建模型

使用 php artisan 创建模型G:\phpstudy\WWW\laravel_base>php artisan make:model Comment

Model created successfully.

3ea2e83a999f569f8f46b1509ef7a10a.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()

4604b4e13334bd6de27d26bbfbce3855.png

关联模型保存数据

057c23052242a7b75e4c0fde0fbcd3ba.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 预加载方式

efe621a9e60b19feab81eeaf7d512021.png

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

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

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

Laravel模型故关联

d7c899b0f57807b0b23b99f769d64cfb.png

0e4d5c445bcc741437fba0f0fee833af.png

826e7308d4723a1185bddaae2e076d87.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值