雄辩的关系返回空数组

时间:2018-07-12 17:21:40

标签: laravel-5 eloquent

我是laravel的新手,我正在尝试获得一些非常基础的东西,但仍然会卡住。

我有两个模型,分别是Post.php和Like.php

我正在尝试使用雄辩的关系来获取链接到帖子的所有赞,但它返回的是一个空数组。这是我的代码-

Post.php

public function likes(){
  return $this->hasMany('App\Like');
}

Route.php

Route::get('/', function(){
  $posts = Post::all()->sortByDesc("post_id");
  return view('index')->with(['posts' => $posts]);
});

View.blade.php

@foreach($posts as $post)
  {{ $post->likes }}
@endforeach

我在这里做什么错了?

更新- 喜欢表迁移

public function up()
{
    Schema::create('likes', function (Blueprint $table) {
        $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', function (Blueprint $table) {
        $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');
    });
}

发布模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{

  public function user(){
    return $this->belongsTo('App\User');
  }

  public function likes(){
    return $this->hasMany('App\Like');
  }
}

1 个答案:

答案 0 :(得分:3)

Laravel期望主键为id,但是您使用的是自定义post_id

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

class Post extends Model {
    protected $primaryKey = 'post_id';

    public function likes() {
        return $this->hasMany('App\Like', 'post_id');
    }
}