Красноречивый пользователь и комментарии - PullRequest
1 голос
/ 14 марта 2019

Использование Mac, Php версии 7.1.19, последней версии Laravel и базы данных SQLite.На сайте есть 3 модели.Пользователь, комментарий и сообщение.Я хотел бы подключить комментарий к пользователю.Таким образом, люди могут видеть свои комментарии на своей панели.База данных должна быть настроена правильно, таблица комментариев имеет ['id', 'user_id', 'body', 'creation_at', 'updated_at'].Ошибка тинкера говорит мне, что он требует возврата, но я добавил возврат к обеим функциям.

Не могли бы вы уточнить, что я в данный момент делаю неправильно?

В User.php,Я поместил функцию комментариев.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Comment;

class User extends Authenticatable
{


  use Notifiable;

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'firstname','lastname','age', 'email', 'password',
];

public function comments()
{
   return $this->hasMany(Comment::class);
}


/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];

/**
 * The attributes that should be cast to native types.
 *
 * @var array
 */
protected $casts = [
    'email_verified_at' => 'datetime',
];
}

В Comment.php я разместил функцию пользователей.

<?php

namespace App;

use App\User;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    public function user()
    {
       return $this->belongsTo(User::class);
    }
}

Обновление, запрашиваемый код модели базы данных:

<?php

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

class CreateCommentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedInteger('user_id');
            $table->string('body');
            $table->timestamps();
        });
    }

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

Код миграции пользователя:

<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('firstname');
            $table->string('lastname');
            $table->integer('age');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->integer('isAdmin')->default(0);
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

При использовании Php Artisan Tinker система выдает следующую ошибку:

App \ User :: first () -> comments LogicException with message 'App / User :: comments должен возвращать экземпляр отношения. '

1 Ответ

1 голос
/ 14 марта 2019

Модель базы данных добавить связь с таблицей users

<?php

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

class CreateCommentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->bigIncrements('id');

            $table->unsignedInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');

            $table->string('body');
            $table->timestamps();
        });
    }

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

Изменить метод комментариев в модели User.php

public function comments()
{
   return $this->hasMany(Comment::class,'user_id','id');
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...