gpt4 book ai didi

laravel-5 - Eloquent 关系返回空数组

转载 作者:行者123 更新时间:2023-12-04 01:54:30 26 4
gpt4 key购买 nike

我是 laravel 的新手,我正在尝试实现一些非常基本的东西,但仍然卡住了。

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

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

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');
}
}

最佳答案

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

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

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

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

关于laravel-5 - Eloquent 关系返回空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51311303/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com