我在类别和帖子表之间有很多关系,如下所示:
分类:
class Category extends Model {
public function posts()
{
//return $this->hasMany('App\Posts','category_id');
return $this->belongsToMany('App\Posts', 'categories_post', 'category_id', 'post_id')
->withTimestamps();
}
}
帖子课程:
class Posts extends Model {
public function category()
{
//return $this->belongsTo('App\Category','category_id');
return $this->belongsToMany('App\Category', 'categories_post', 'post_id', 'category_id')
->withTimestamps();
}
}
当我只需要访问一个类别的帖子时,我会在我的控制器中执行此操作:
public function cat($category_id)
{
$posts= $category_id->posts()->paginate(7);
return view('cat')->with('posts',$posts);
}
修改
要做到这一点,我在" RouteServiceProvider.php"中添加了这个。文件:
public function boot(Router $router)
{
parent::boot($router);
$router->model('categories','App\Category');
}
这完美无缺。问题是,我有另一个控制器应该获得多个类别的帖子:
public function index()
{
$title = 'news';
$categories= [1, 2, 10, 11];
// Here is the problem:
$posts= $categories->posts()->paginate(7);
return view('news')->with('posts',$posts)->with('title',$title);
}
这给了我这个错误:调用非对象上的成员函数posts()
我知道调用数组有问题,但我不知道如何解决它。任何人都可以帮助我:)
public function index()
{
$title = 'news';
$category_ids = [1, 2, 10, 11];
$posts = Posts::whereHas('category', function($query) use ($category_ids) {
$query->whereIn('id', $category_ids);
})->get();
return view('news')->with('posts',$posts)->with('title',$title);
}
答案 0 :(得分:3)
您可以执行以下操作:
$category_ids = [1, 2, 10, 11];
$posts = Post::whereHas('categories', function($query) use ($category_ids) {
$query->whereIn('id', $category_ids);
});
请参阅this。