Laravel调用sync方法报错‘Method sync does not exist’问题求助
问题排查与解决方案
嘿,我帮你找到了两个导致这个报错的核心问题,咱们一步步来修复:
1. Category模型的关联定义错误
先看你的Category模型里的posts关联:
public function posts(){ return $this->belongsToMany('App\Model\User\Category','category__posts', 'post_id', 'category_id'); }
这里有两个明显错误:
- 第一个参数应该是关联的Post模型,而不是Category自己,否则Laravel无法识别正确的多对多关联关系
- 外键顺序搞反了:
belongsToMany的参数顺序是「关联模型、中间表、当前模型的外键、关联模型的外键」,所以Category的posts关联里,当前模型是Category,对应中间表的category_id,关联模型是Post,对应post_id,顺序要调换
修正后的Category模型代码:
<?php namespace App\Model\User; use Illuminate\Database\Eloquent\Model; class Category extends Model { public function posts(){ return $this->belongsToMany( 'App\Model\User\Post', 'category__posts', 'category_id', 'post_id' ); } }
2. 调用sync时误用了属性而非关联方法
在你的PostController里,你写的是:
$post->tags->sync($request->tags); $post->categories->sync($request->categories);
这里的$post->tags和$post->categories是已加载的Eloquent集合对象(Illuminate\Database\Eloquent\Collection),这个类并没有sync方法。而sync是BelongsToMany关联实例的方法,你需要调用关联方法(带括号)来获取这个实例。
修正后的Controller代码:
try{ $post = new Post; $post->title = $request->title; $post->subtitle = $request->subtitle; $post->slug = $request->slug; $post->body = $request->body; $post->status = 1; $post->save(); // 改成带括号的关联方法调用 $post->tags()->sync($request->tags); $post->categories()->sync($request->categories); } catch(\Exception $e){ return redirect(route('post.index'))->with('message', '添加文章失败!'.$e->getMessage()); }
额外检查点
最后确认你的中间表结构是否正确:
post__tags表需要包含post_id和tag_id两个外键,分别关联posts.id和tags.idcategory__posts表需要包含category_id和post_id两个外键,分别关联categories.id和posts.id
把这两处错误修正后,你的标签和分类同步逻辑应该就能正常运行了。
内容的提问来源于stack exchange,提问作者Singh V
相关产品推荐
相关产品推荐

