Php 检查类别是否属于post
您好,我正在尝试制作显示所有类别的脚本,如果类别属于post,则应使用复选框选中此类别。我的剧本不行,你能帮帮我吗。当必须显示两个类别时,它仅显示一个选中类别。 类别模型:Php 检查类别是否属于post,php,laravel,laravel-4,eloquent,Php,Laravel,Laravel 4,Eloquent,您好,我正在尝试制作显示所有类别的脚本,如果类别属于post,则应使用复选框选中此类别。我的剧本不行,你能帮帮我吗。当必须显示两个类别时,它仅显示一个选中类别。 类别模型: class Category extends Eloquent { protected $table= "categories"; public function posts(){ return $this->belongsToMany('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');
}
}
catRelation:
[{"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”}
一个类别不应该属于一个帖子,但是,一篇文章应该属于一个类别
我假设catRelation
是您的透视表。你不需要id
,在
处创建或在
处更新就可以了
示例模型:
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');
}
}
注意:我可能在
中的最后一个参数是错误的。我还有一个问题。在使用Category::with('posts')->get()之后;如何在视图中显示所有类别,并检查与当前帖子id相关的类别?