[英]Couldn't access data in laravel 5.8 from 1 to many relationship
I new to laravel.我是 laravel 的新手。 I have been trying to set a 1 to many realtionship between post and category, I can access the category using the post_id but not the reverse.
我一直在尝试在帖子和类别之间设置 1 到多个关系,我可以使用 post_id 访问类别,但不能反过来。 I get the following error,
我收到以下错误,
"Trying to get property 'category' of non-object" “试图获取非对象的属性‘类别’”
This is my web.php这是我的 web.php
<?php
use App\Post;
Route::get('/test',function()
{
return App\Post::find(3)->category;
});
This is from post.php这是来自post.php
public function category()
{
return $this->belongsTo('App\Category');
}
This is from category.php这是来自类别。php
public function posts()
{
return $this->hasMany('App\Post');
}
This is Post.php这是 Post.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Softdeletes;
class Post extends Model
{
protected $fillable =[
'title', 'content', 'category_id', 'featured', 'slug'
];
public function category()
{
return $this->belongsTo('App\Category');
}
public function tag()
{
return $this-> belongsToMany('App\Tag');
}
use SoftDeletes;
public function getFeaturedAttribute($featured)
{
return asset($featured);
}
.......
This is Category.php这是类别。php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = ['name'];
public function posts()
{
return $this->hasMany('App\Post');
}
}
The find method finds a model that has a given primary key. find 方法查找具有给定主键的 model。 In your web.php
App\Category::find(7)
returns a category instance of id 7. I'm guessing what you are trying to do is App\Post::find(7)->category
in other word you are trying to retrieve the post of id 7 and get its category;在您的 web.php
App\Category::find(7)
中返回 id 7 的类别实例。我猜您正在尝试做的是App\Post::find(7)->category
换句话说,您是尝试检索 id 7 的帖子并获取其类别; If not you are probably trying to access the posts of one category of id 7 in which case you should code App\Category::find(7)->posts
.如果不是,您可能正在尝试访问 id 为 7 的一类帖子,在这种情况下,您应该编写
App\Category::find(7)->posts
代码。
maybe you need App\Category::find(7)->posts because Category model really doesn't have category property也许您需要 App\Category::find(7)->posts 因为类别 model 确实没有类别属性
I don't know what the problem was I closed everything and restarted.我不知道问题是什么,我关闭了所有内容并重新启动。 Everything worked fine.
一切正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.