Php 以多对多关系将数组传递给控制器-laravel
我在类别和帖子表之间有一个多对多关系,如下所示: 类别类别:Php 以多对多关系将数组传递给控制器-laravel,php,laravel,many-to-many,Php,Laravel,Many To Many,我在类别和帖子表之间有一个多对多关系,如下所示: 类别类别: 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') -&
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 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()
我知道调用数组有问题,但我不知道如何解决。谁能帮我一下吗:)
解决方案 在托马斯·范德文(Thomas Van der Veen)回答后,我想出了一个工作完美的控制器:
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);
}
你可以这样做:
$category_ids = [1, 2, 10, 11];
$posts = Post::whereHas('categories', function($query) use ($category_ids) {
$query->whereIn('id', $category_ids);
});
请参阅。$categories仅仅是一个数字数组?它根本没有链接到您的类别模型,甚至不知道如何在id上调用$categorie_id->posts()?它是一个intger吗?应该是一个对象,尽管
$posts=\App\Category::find($Category\u id)->posts()->paginate(7)代码>我编辑了我的问题,向您展示了我是如何制作$categorie\u id->posts()
工作的。非常感谢您,这真的帮助了我。我将更新我的问题以添加最终控制器
$category_ids = [1, 2, 10, 11];
$posts = Post::whereHas('categories', function($query) use ($category_ids) {
$query->whereIn('id', $category_ids);
});