2016-12-24 66 views
-2

我試圖調用基於類別的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'); 
    } 
} 
+0

該關係應該是'belongsToMany'而不是'belongsTo'。 –

回答

0

您可以使用whereHas爲:

$category = Category::where('internal_name',$category)->first(); 

$posts = Post::whereHas('categories', function($q) use($category) { 
    $q->where('category_id',$category->id); 
})->get(); 

或者

$category = Category::where('internal_name',$category)->first(); 
$posts = $category->posts; 

The whereHas method is used to put "where" conditions on your has queries.

1

首先,如果關係是多對多(您正在使用數據透視表)的關係應該是belongsToMany(),但不belongsTo()

加載關係您應該使用with()方法。例如,如果你想加載一個類別的所有帖子:

Post::where('category_id', $category->id)->with('categories')->first();