php – 试图获取非对象的属性错误 – Laravel
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php – 试图获取非对象的属性错误 – Laravel,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2158字,纯文字阅读大概需要4分钟。
内容图文
![php – 试图获取非对象的属性错误 – Laravel](/upload/InfoBanner/zyjiaocheng/729/8ea31c7624a448e2a8798206e3d3f755.jpg)
参见英文答案 > Laravel Foreign Key ‘Trying to get property of non-object’ 1个
我正在开发一个laravel的博客,我在两个表之间的外键有问题:帖子和类别.
我创建了两个模型:Post(用于posts表)和Category(用于categories表).在我看来,我写了这段代码:< p>张贴于:{{$post-> category-> id}}< / p>,但是显示以下错误:
ErrorException: Trying to get property of non-object foreign key error
邮政模式:
class Post extends Model
{
public function category()
{
return $this->belongsTo('App\Category');
}
}
分类型号:
class Category extends Model
{
public $table = 'categories';
public function posts()
{
return $this->hasMany('App\Post');
}
}
查看表格:
@extends('main')
@section('title', "| $post->title " )
@section('content')
<div class="row">
<div class ="col-md-8></col-md-8 col-md-offset-2">
<h1>{{$post->title}}</h1>
<p>{{$post->body}}</p>
<hr>
<p>Posted In:{{$post->category->id}}</p>
</div>
</div>
@endsection
我希望代码:< p>张贴于:{{$post-> category-> id}}< / p>
将在博客文章中输出该类别.
解决方法:
TL; DR
我很确定这必须与Laravel 5.8中的新默认值相关,其中主键已从Integer更改为BigInteger.
如果是这样,请从以下位置更改外键列类型:
$table->unsignedInteger('category_id');
至:
$table->unsignedBigInteger('category_id);
^^^
说明
在以前版本的Laravel(5.7或更低版??本)中,这是默认行为:
Schema::create('categories', function(Blueprint $table) {
$table->increments('id'); // <-- so, an 'integer'
// ...
});
那么在你的其他表中你就是这样做的:
Schema::create('posts', function(Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('category_id'); // <-- to match, also an integer
// or this: $table->integer('category_id')->unsigned();
// ...
});
但是现在在Laravel 5.8中,默认迁移看起来像:
Schema::create('categories', function(Blueprint $table) {
$table->bigIncrements('id'); // <----- so now is a BigInteger
// ...
});
哪个是BigInteger.所以在你的外键中你应该使用这种类型:
Schema::create('posts', function(Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('category_id'); // <---- to match, use this
// or this: $table->bigInteger('category_id')->unsigned();
// ...
});
查看Povilas Korop的这篇文章:Be Careful: Laravel 5.8 Added bigIncrements As Defaults
内容总结
以上是互联网集市为您收集整理的php – 试图获取非对象的属性错误 – Laravel全部内容,希望文章能够帮你解决php – 试图获取非对象的属性错误 – Laravel所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。