Laravel 5 返回空数组的雄辩关系

Laravel 5 返回空数组的雄辩关系,laravel-5,eloquent,Laravel 5,Eloquent,我是拉雷维尔的新手,我正在努力实现一些非常基本的东西,但还是被卡住了 我有两个模型,即Post.php和Like.php 我试图使用雄辩的关系获取所有链接到帖子的喜欢,但它返回的是一个空数组。这是我的密码- Post.php public函数likes(){ 返回$this->hasMany('App\Like'); } Route.php Route::get('/',function(){ $posts=Post::all()->sortByDesc(“Post_id”); 返回视图('i

我是拉雷维尔的新手,我正在努力实现一些非常基本的东西,但还是被卡住了

我有两个模型,即Post.php和Like.php

我试图使用雄辩的关系获取所有链接到帖子的喜欢,但它返回的是一个空数组。这是我的密码-

Post.php

public函数likes(){
返回$this->hasMany('App\Like');
}
Route.php

Route::get('/',function(){
$posts=Post::all()->sortByDesc(“Post_id”);
返回视图('index')->带有(['posts'=>$posts]);
});
View.blade.php

@foreach($posts as$post)
{{$post->likes}
@endforeach
我做错了什么

更新- 喜欢表迁移

public function up()
{
Schema::create('likes',函数(Blueprint$表){
$table->increments('like_id');
$table->integer('post_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->foreign('post_id')->references('post_id')->on('posts')->onDelete('cascade');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
}
迁移后

public function up()
{
Schema::create('posts',函数(Blueprint$表){
$table->increments('post_id');
$table->integer('user_id')->unsigned();
$table->string('post_message');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
后期模型


Laravel希望主键是
id
,但您使用的是自定义
post\u id

在模型中指定并调整关系:

类后扩展模型{
受保护的$primaryKey='post_id';
公共职能{
返回$this->hasMany('App\Like','post_id');
}
}

请发布
likes
表迁移。我在问题
$table->increments('like_id')的更新部分添加了likes表迁移将其更改为
$table->increments('id')
我已将其更改为id,但它仍然返回相同的[]null结果
{{$post->likes->count()}
的结果是什么?
这返回一个错误-
未找到列:1054未知列'likes.post\u id'在'where子句'
中,Laravel是否拾取了一个专门称为$primaryKey的变量?是的,您可以覆盖默认值: