Php Laravel注释和用户关系返回null
我试图在我的网站上实现评论系统,但我在处理人际关系方面遇到了困难。出于某种原因,当我试图从comment类访问用户关系时,它返回null。。我的代码: Post.php User.phpPhp Laravel注释和用户关系返回null,php,laravel,Php,Laravel,我试图在我的网站上实现评论系统,但我在处理人际关系方面遇到了困难。出于某种原因,当我试图从comment类访问用户关系时,它返回null。。我的代码: Post.php User.php class User extends Model implements Authenticatable { use AuthenticableTrait; protected $primaryKey = 'username'; public $incrementing = false; publ
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
使用返回关键字
public function user()
{
return $this->belongsTo(User::class,'username') ;
}
public function post()
{
return $this->belongsTo(Post::class,'post_id');
}
在user和post函数中,您省略了return关键字。意思是你什么都不回来我的上帝。。。我真不敢相信我会这么蠢,你不会。我们每个人都会遇到这种情况。哈哈,谢谢,但我昨晚熬夜试图解决这个问题30分钟XD
public function user()
{
return $this->belongsTo(User::class,'username') ;
}
public function post()
{
return $this->belongsTo(Post::class,'post_id');
}
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'));
}