Laravel注释和用户关系返回null

时间:2017-03-31 09:41:32

标签: php laravel

我正在尝试在我的网站上实施评论系统,但我很难处理这些关系。出于某种原因,当我尝试从注释类访问用户关系时,它返回null ..我的代码: post.php中

    class Post extends Model
{
    public $timestamps = false;
    public $primaryKey = 'post_id';
    protected $fillable = ['title','created_at','username','image'];
    public function user()
    {
      return $this->belongsTo(User::class,'username');
    }
    public function votes()
    {
      //Quick note: Id refers to the post id.
      return $this->hasMany(PostVotes::class,'post_id');
    }
    public function comments()
    {
      return $this->hasMany(Comment::class,'post_id');
    }
}

user.php的

class User extends Model implements Authenticatable
{
  use AuthenticableTrait;
  protected $primaryKey = 'username';
  public $incrementing = false;
  public $timestamps = false;
  protected $fillable = ['username','email','password','created_at','avatar','about'];
  // Gets avatar to display on navbar.
  public function posts()
  {
    return $this->hasMany(Post::class,'username');
  }
  public function comments()
  {
    return $this->hasMany(Comment::class,'username');  
  }
  public static function getAvatar()
  {
     return self::Where('username', '=', Session::get('username'))->value('avatar');
  }

}

Comment.php

    class Comment extends Model
{
    public $timestamps = false;
    public $primaryKey = 'post_id';
    protected $fillable = ['comment','created_at','post_id','username'];
    public function user()
    {
        $this->belongsTo(User::class,'username') ;
    }
    public function post()
    {
        $this->belongsTo(Post::class,'post_id');
    }
}
public function view($post_id)
   {
      $post = Post::with('comments')->findOrFail($post_id);
      return view('posts.view',compact('post'));
   }
  @foreach($post->comments as $comment)
 // null
 {{dd($comment->user())}}
@endforeach

2 个答案:

答案 0 :(得分:3)

错过了返回关键字

public function user()
{
    return $this->belongsTo(User::class,'username') ;
}

public function post()
{
    return $this->belongsTo(Post::class,'post_id');
}

答案 1 :(得分:0)

    public function displaycomment($id) {
        $data['comment'] = comment::select('comments.id', 'comments.description', 'users.name', 'comments.created_at', 'comments.post_id')->where('post_id',$id)->leftjoin('users', 'users.id', '=', 'comments.user_id')->get();
//        dd($data);
        return view('displayblog',  compact('data'));
    }