我编写了一个名为Categorizable
的类,它允许在扩展它的类和类Category
之间建立多对多关系。它工作得很好,但我注意到,如果我调用一个方法将类别添加到可分类对象,它会在连接表上添加条目,但我的实际对象不会更新。如果我尝试在我的对象上调用categories
,则不会更新数据库中的内容。我想保持我的对象是最新的,所以每次添加类别时我都不必查询数据库。
Categorizable.php
class Categorizable extends Model{
public function categories(){
return $this->morphToMany(Category::class, 'categorizable');
}
public function addCategory(\App\Category $category){
if ( $this->isValidCategory($category) ){
if ( $this->hasCategory($category) ){
return false;
}
else{
$this->categories()->save($category);
return true;
}
}
else{
return false;
}
}
public function removeCategory(\App\Category $category){
if ( $this->isValidCategory($category) ) {
if ($this->hasCategory($category)) {
$this->categories()->detach($category);
return true;
}
else {
return false;
}
}
else{
return false;
}
}
public function hasCategory(\App\Category $category){
return $this->categories->contains($category);
}
public function isValidCategory(\App\Category $category){
if ( $category->category_type === get_class( $this ) ){
return true;
}
else{
return false;
}
}
如果使用Laravel 5.2无法做到这一点或被认为是不良做法,请说明。如果您对如何改进这一点有任何建议,那也是受欢迎的。感谢。
答案 0 :(得分:0)
考虑在控制器中处理此问题,如https://laravel.com/docs/5.4/eloquent-relationships#updating-many-to-many-relationships
中所述它将简化您想要实现的目标。我们假设类别与文章相关,控制器是ArticleController。 $ article是模型对象,isValidCategory()检查完成。添加类别或删除一个类别:
$article->categories()->attach($category->id);
$article->categories()->detach($category->id);
重置该文章的所有关系:
$article->categories()->detach();
$article->categories()->attach($categories); //flat array
或者在一行中执行此操作:
$article->categories()->sync($categories);
请记住,您可以使用一个 ID或数组的ID,如[1,2,3]
注意: $category->id
是一个假设,如果$ category是id,那么很明显,使用$category