代码之家  ›  专栏  ›  技术社区  ›  ujjwal verma

返回空数组的雄辩关系

  •  0
  • ujjwal verma  · 技术社区  · 7 年前

    我是新来的拉勒维尔,我正在努力实现一些非常基本的东西,但仍然陷入困境。

    我有两个模型,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 回复  |  直到 7 年前
        1
  •  3
  •   Jonas Staudenmeir    7 年前

    拉维尔希望主键是 id ,但您正在使用自定义 post_id 是的。

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

    class Post extends Model {
        protected $primaryKey = 'post_id';
    
        public function likes() {
            return $this->hasMany('App\Like', 'post_id');
        }
    }