检查类别是否属于帖子


Check if category belongs to post

您好,我正在尝试制作显示所有类别的脚本,如果类别属于发布此类别,则应使用复选框进行检查。我的脚本不起作用,你能帮我吗?当必须显示两个时,它只显示一个选中的类别。控制器类别型号:

class Category extends Eloquent {
    protected $table= "categories";
    public function posts(){
        return $this->belongsToMany('Post');
    }
}

发布模型

class Post extends Eloquent {
    protected $table = 'posts';
    public function categories(){
        return $this->belongsToMany('Category');
    }
}

猫关系:

[{"id":"45","post_id":"132","category_id":"1","created_at":"2014-12-26 20:32:41","updated_at":"2014-12-26 20:32:41"},{"id":"46","post_id":"132","category_id":"3","created_at":"2014-12-26 20:32:41","updated_at":"2014-12-26 20:32:41"}]

所有类别: [{"id":"1","name":"Laravel","slug":"laravel","created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00"},{"id":"3","name":"PHP","slug":"php","created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00"}]

类别不应该属于帖子,而应该属于一个类别。

我假设catRelation是你的数据透视表。你不需要idcreated_atupdated_at,这是毫无价值的。

示例模型:

class Post extends Eloquent 
{
    protected $table = 'posts';
    public function category()
    {
        return $this->belongsToMany('Category', 'catRelation', 'category_id');
    }
}
class Category extends Eloquent
{
    protected $table = 'categories';
    public function post()
    {
        return $this->belongsToMany('Post', 'catRelation', 'post_id');
    }
}

注意:我可能以错误的方式得到了belongsToMany最终论点。