您好我试图创建显示所有类别的脚本,如果类别属于post,则应使用复选框选中此类别。我的剧本不会有用,请你帮我。当必须显示两个时,它只显示一个选中的类别。 Controller类别模型:
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:00"}]
答案 0 :(得分:1)
一个类别不应该属于一个帖子,而是一个帖子应该属于一个类别。
我认为catRelation
是您的数据透视表。对于此,您不需要id
,created_at
或updated_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
中获得了最终论据。