我正在关注laravel教程,并创建了一个表单,以便使用user_id创建对帖子的评论。我似乎无法理解我如何传递user_id。发送用户ID和发帖ID
Post
模型
class Post extends Model
{
protected $guarded = [];
public function comments()
{
return $this->hasMany(Comment::class);
}
public function addComment($body)
{
$this->comments()->create(compact('body'));
}
public function user()
{
return $this->belongsTo(User::class);
}
}
Comment
模型
class Comment extends Model
{
protected $guarded = [];
public function post()
{
$this->belongsTo(Post::class);
}
public function user()
{
$this->belongsTo(User::class);
}
}
User
模型
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 posts()
{
return $this->hasMany(Post::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
public function publish(Post $post)
{
$this->posts()->save($post);
}
}
CommentsController.php
class CommentsController extends Controller
{
public function store(Post $post)
{
$this->validate(request(), ['body' => 'required|min:2']);
$post->addComment(request('body'));
return back();
}
}
正如你所看到的,我在Post
模型中调用->addComment
来添加评论。它工作得很好,直到我将user_id添加到Comments
表中。什么是存储用户ID的最佳方式?我无法让它工作。
它的工作原理。但是,有没有更好的方法来做到这一点?例如,我在'user'模型中用'publish function'提交我的文章。它自动获取user_id。 – twoam
@JustinTime检查我的更新! – Maraboc
我打电话给未定义的方法Illuminate \ Database \ Query \ Builder :: comments() – twoam