php - App\Post::categorys 必须返回一个关系实例,但返回的是“null”。是否使用了“return”关键字?拉拉维尔
问题描述
我不明白为什么它不起作用,这几天一直在做。我正在制作一个显示产品的网站,每个产品都有一个类别,所以我与帖子和类别表建立了关系,但它一直给出这个错误 App\Post::categorys must return a relationship instance, but "null" was returned。是否使用了“return”关键字?
Post.php: (this is the modal section for Post)
public function categorys(){
$this->hasOne(Category::class);
}
Category.php: (this is the modal section for Category)
public function posts(){
$this->hasMany(Post::class);
}
index.blade.php: (index section to display the name of the categories)
{{ $posts->categorys->name }}
***SOLVED*** added return! But now its giving me another problem
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'categories.post_id' in 'where clause' (SQL: select * from categories where categories.post_id = 1 and categories.post_id is not null limit 1) sorry I am new in Laravel
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('name');
$table->text('description');
$table->integer('category_id');
$table->integer('price');
});
}
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('name');
});
}
It keeps giving the error i dont know what seems to be the problem
解决方案
您需要返回关系。喜欢
public function categorys(){
$this->hasOne(Category::class);
}
应该成为
public function categorys(){
return $this->hasOne(Category::class);
}
推荐阅读
- string - 是否有一个字符串函数可以分隔用斜杠连接的单词?
- openpyxl - XlsxWriter 中的追加模式损坏现有文件
- webpack - Webpack css-loader UnhandledPromiseRejectionWarning: Error: The module created for a LoaderDependency must have an original source
- javascript - 从 Web 应用程序中的过滤数组自动完成
- php - MYSQL SELECT 多行成一行
- r - 如何计算与连续函数的平均密度相对应的 x 值?
- flutter - Flutter 中的抽屉到底部导航栏
- python - 如何将字符串的字符定义为“索引”,然后计算两个方向的字符频率?
- python - 如何在 python 中使用用户输入和字符串操作制作框架框?
- c# - C# DateTime 格式化输出 01/01/2000