Laravel 5.7数据库关系不起作用

时间:2019-01-28 21:32:56

标签: database laravel migration

我在数据库中有两个表,分别是'Users'和另一个'Discussion。 用户模型为

class User extends Authenticatable{

protected $fillable = [
    'name', 'email', 'password',
];


protected $hidden = [
    'password', 'remember_token',
];

public function Discussion()
{
    return $this->hasMany('app\Discussion');
}}

用户迁移表为:

  public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('avatar');
        $table->boolean('admin')->default(0);
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}

讨论模型是:

class Discussion extends Model{
protected $fillable = ['title','content', 'slug' ,'user_id', 'channel_id'];

public function Reply()
{
    return $this->hasMany('app\Reply');
}

public function user()
{
    return $this->belongsTo('app\User');
}

public function Channel()
{
    return $this->belongsTo('app\Channel');
}}

讨论迁移表:

 public function up()
{
    Schema::create('discussions', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->integer('channel_id')->unsigned();
        $table->string('title');
        $table->text('content');
        $table->text('slug');
        $table->timestamps();
    });
}

控制器返回:

 public function show($slug)
{

    return view('discussion.show')->with('post',Discussion::where('slug',$slug)->first());

}

现在,当我尝试检索组合数据时,

<h1>$post->user->name</h1>

它显示了我

ErrorException (E_ERROR) Class 'app\User' not found

我没有得到确切的问题。有人可以帮忙解决问题吗?

1 个答案:

答案 0 :(得分:0)

能否在“讨论”和“用户”表中提供记录列表?另外,还要在“讨论”模型中仔细检查您的课程参考。我猜想您希望“ App”为大写字母,而不是“ app \ User”。除非您有意更改了App命名空间,否则默认情况下会默认将其设置为大写字母“ A”。