2017-07-21 123 views
2

我正在关注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的最佳方式?我无法让它工作。

回答

0

更新您的addComment方法:

public function addComment($body) 
{ 
    $user_id = Auth::user()->id; 
    $this->comments()->create(compact('body', 'user_id')); 
} 

PS:假设用户进行身份验证。

UPDATE

public function addComment($body) 
{ 
    $comment = new Comment; 
    $comment->fill(compact('body')); 
    $this->comments()->save($comment); 
} 

没有savingit创建注释的新实例,你只需要保存的注释在后,因为一个帖子已经属于用户

+0

它的工作原理。但是,有没有更好的方法来做到这一点?例如,我在'user'模型中用'publish function'提交我的文章。它自动获取user_id。 – twoam

+0

@JustinTime检查我的更新! – Maraboc

+0

我打电话给未定义的方法Illuminate \ Database \ Query \ Builder :: comments() – twoam

0

有没有必要手工处理的ID,让雄辩为您处理:

$user = Auth::user(); // or $request->user() 
$user->comments()->save(new Comment()); 

more information about saving eloquent models.

+0

如果我这样做,它开始要求post_id。我该如何处理好口才? – twoam

+0

'新评论()'只是一个示例占位符。评论对象应该事先创建,您可以使用相同的结构来保存评论到帖子。 – Ali