问题描述
我有两个模型
管理员模型 -> 我用来保存管理员在里面,我在 admin.PHP 中创建了 Guard 管理员和他自己的路由
用户模型(laravel 中的默认值)-> 我用来在其中保存普通用户以及在 web.PHP 中他自己的路由
评论模型:
$table->id();
$table->string('comment');
$table->boolean('approved')->default(0);
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->unsignedBigInteger('post_id');
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
当普通用户在帖子上添加评论时,将其保存在用户模型中的 user_id 中 问题是:我想在添加评论或回复时也让管理员保存他的 ID? 我想知道我是否应该像这样在评论模型上或者什么解决方案:
$table->unsignedBigInteger('admin_id');
$table->foreign('admin_id')->references('id')->on('admins')->onDelete('cascade');
感谢兄弟的帮助。
解决方法
试试这个,
首先创建一个表:-
php artisan make:migration create_comments_table
$table->id();
$table->string('comment')->nullable();
$table->boolean('approved')->default(0);
$table->unsignedBigInteger('user_id')->nullable();
$table->unsignedBigInteger('admin_id')->nullable();
$table->unsignedBigInteger('post_id')->nullable();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->foreign('admin_id')->references('id')->on('admins')->onDelete('cascade');
然后在reply_id字段后添加评论表:-
php artisan make:migration add_reply_id --table=comments // table name
$table->id();
$table->unsignedBigInteger('reply_id')->nullable();
$table->foreign('reply_id')->references('id')->on('comments')->onDelete('cascade')->onUpdate('cascade');
评论模型:-
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $table = 'comments';
protected $guarded = [];
public function post()
{
return $this->BelongsTo('App\Models\Post','post_id');
}
public function user()
{
return $this->BelongsTo('App\User','user_id');
}
public function admin()
{
return $this->BelongsTo('App\Admin','admin_id');
}
public function replies()
{
return $this->hasMany('App\Models\Comment','reply_id');
}
public function reply()
{
return $this->BelongsTo('App\Models\Comment','reply_id');
}
}
数据库中像这样的数据存储:-