hi我想在我的projectDetail组件中构建注释系统但当我尝试将注释存储在DB中时显示错误[1048 Column'commentable_id'不能为null]这是我的ProjectDeatil.vue脚本:
<script>
export default {
data(){
return{
key: this.$route.params.id,
projets:[],
projet:{
id:'',
name:'',
durre:'',
description:'',
budget:'',
owner:'',
},
membres:[],
membre:{
id :'',
membre:'',
projet_id:'',
},
form : new Form({
id:'',
body:''
})
}
},
methods:{
afficherProjets(){
axios.get('/api/getProjects')
.then(({data}) => {this.projets=data.data});
},
afficherMembre(){
axios.get('/api/membreid').then(({data})=> {this.membres =data.data});
},
ajouterCommentaire(){
this.form.post('/api/comments/'+this.key).then(()=>{
this.form.reset()})
}
},
mounted() {
console.log('Component mounted.')
this.afficherProjets();
this.afficherMembre();
}
}
</script>
这是我的CommentController函数:
public function store($key){
//$data =$request->all();
$projet=new Projet;
$commentaire =new Commentaire;
$commentaire->user_id= auth()->user()->id;
$commentaire->body= request('body');
$commentaire->commentable_id = $key;
$projet->comments()->save($commentaire);
}
这是我在模型注释中的函数:
public function commentable(){
return $this->morphTo();
}
这是我在模型项目中的功能:
public function comments(){
return $this->morphMany('AppCommentaire','commentable')->latest();
}
这是我的路线:
Route::post('/comments/{key}', 'APICommentController@store');
当您在Laravel中对多态关系调用->save()
时,Eloquent会神奇地为您添加正确的字段,在这种情况下,它将是commentable_id
,因此如果您正在执行->comments()->save()
,则不需要设置该字段。但是,您应该做的是从数据库中获取Projet
,然后运行代码。
当您新建一个Projet
实例时,Eloquent不知道这在数据库中与什么有关,所以它试图用null
的commentable_id
来保存它。更换此线路
$projet=new Projet;
使用一行可以从数据库中为您获取Projet
的正确实例,例如:
$projet = Projet::find($key); // Assuming $key is the primary key of your Projet model.
(为免生疑问,我还建议删除线路$commentaire->commentable_id = $key;
。(