我有三个模型,我创建了Post和Comment以及User。我试图在两者之间建立一种关系。评论和发布他们都有一个字段“user_id”匹配用户表上的ID。下面是关系,我想设置:Laravel belongsTo关系不起作用
Comment.php:
<?php
namespace App;
class Comment extends Model
{
//
public function post(){
return $this->belongsTo(Post::class);
}
public function user(){
return $this->belongsTo(User::class);
}
}
post.php中:
<?php
namespace App;
class Post extends Model
{
public function comments(){
return $this->hasMany(Comment::class);
}
public function addComment($body, $name, $email){
$this->comments()->create(compact('body','name','email'));
}
public function user(){ // $comment->user->name
return $this->belongsTo(User::class);
}
}
user.php的现在
<?php
namespace App;
use App\Post;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function post(){
return $this->hasMany(Post::class);
}
}
你可以看到一条评论属于一个用户,一条帖子属于一个用户。
但是,当我尝试通过修补程序创建一个新的职位(没有用户创建数据库或登录用户)我可以创建一个没有问题的职位;
这告诉我,一个职位必须有一个用户和一个评论的关系必须有一个用户以及它不工作!任何想法如何解决这个问题?
迁移:
create_posts_migration:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->string('title');
$table->text('body');
$table->string('image');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
create_comment_migration:
<?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->increments('id');
$table->integer('post_id');
$table->integer('user_id');
$table->string('email');
$table->string('name');
$table->string('body');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('comments');
}
}
请显示您的User.php文件。 –
我编辑帖子,让它现在在那里 –
检查您是否在'posts'表中添加了'user_id'列。 –