我試圖調用基於類別的os帖子,但它沒有工作,給我錯誤:Non-static method App\Category::posts() should not be called statically, assuming $this from incompatible context
。 我已經嘗試過從雙方調用,拋出後模型methodos或類別,但相同的錯誤消息。可以弄清楚我做錯了什麼。根據類別調用帖子列表
數據庫:
Posts:
-id;
-title;
-text;
Categories:
-id;
-name;
-internal_name;
category_post:
-id;
-post_id;
-category_id
控制器:
public function categoryPostList($category)
{
$category = Category::posts()->where('internal_name',$category)->first();
$posts = Post::categories()->where('category_id',$category->id)->get();
dd($posts)
}
型號帖子:
class Post extends Model
{
public function categories()
{
return $this->belongsToMany(Category::class);
}
}
型號類別:
class Category extends Model
{
public function posts()
{
return $this->belongsTo('App\Post');
}
}
該關係應該是'belongsToMany'而不是'belongsTo'。 –