我是 Laravel 新手。我一直在尝试在帖子和类别之间设置一对多的关系,我可以使用 post_id 访问类别,但反之则不行。我收到以下错误,
“试图获取非对象的属性‘类别’”
这是我的 web.php
<?php
use App\Post;
Route::get('/test',function()
{
return App\Post::find(3)->category;
});
这是来自 post.php
public function category()
{
return $this->belongsTo('App\Category');
}
这是来自category.php
public function posts()
{
return $this->hasMany('App\Post');
}
这是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);
}
.......
这是类别.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = ['name'];
public function posts()
{
return $this->hasMany('App\Post');
}
}
守着星空守着你
胡子哥哥
慕仙森