Laravel 连接帖子和类别
Laravel Connect Posts and Categories
我有三张表
Posts with ID
Post_Categories with ID, Post_ID and Category_id
Categories with ID
我需要获取某一特定类别的所有类别post有人可以帮助我吗?
这是经典的多对多关系,在Laravel
中是这样的:
class Post
{
function categories()
{
return $this->belongsToMany('Category', 'Post_Categories');
}
}
将此代码添加到帖子模型中
public function categories()
{
return $this->belongsToMany('Category', 'categories_posts','Category_ID','Post_ID') ;
}
然后要提取一个 post 的所有类别,您只需这样做
$myPost = Post::find(idPost);
$myPost->categories ;
我有三张表
Posts with ID
Post_Categories with ID, Post_ID and Category_id
Categories with ID
我需要获取某一特定类别的所有类别post有人可以帮助我吗?
这是经典的多对多关系,在Laravel
中是这样的:
class Post
{
function categories()
{
return $this->belongsToMany('Category', 'Post_Categories');
}
}
将此代码添加到帖子模型中
public function categories()
{
return $this->belongsToMany('Category', 'categories_posts','Category_ID','Post_ID') ;
}
然后要提取一个 post 的所有类别,您只需这样做
$myPost = Post::find(idPost);
$myPost->categories ;