【问题标题】:Problem with relationship Model Comments in Laravel 7Laravel 7中的关系模型注释问题
【发布时间】:2021-03-26 11:03:00
【问题描述】:

我有两个模型

Admin Model -> 我用来将 Admins 保存在其中,并在 admin.php 中创建 Guard admin 和他自己的路由

用户模型(在 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');

谢谢你的帮助兄弟。

【问题讨论】:

  • 不需要添加单独的列,您可能在用户表中有一个角色,该角色描述了用户类型,无论是用户还是管理员,因此您可以将评论者的 id 与 id 进行比较在用户表中并获取类型

标签: laravel model relation


【解决方案1】:

试试这个,

首先创建一个表:-

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');

然后在 cmets 表中添加 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');
    }
}

数据库中这样的数据存储:-

【讨论】:

  • 谢谢你的兄弟,我会再试一个问题,兄弟,这是制作这样的好方法吗,或者你有其他方法可以告诉我我可以做到吗
  • 是的,这是一个好方法,因为您可以轻松获取数据。例如,您可以找到发布主评论,您可以轻松获取 Post::where('id',1)->with(['reply' => function($q) { $q->where('reply_id',null ); }])->get();
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-30
  • 2019-08-11
  • 1970-01-01
  • 2015-10-02
  • 1970-01-01
相关资源
最近更新 更多