【发布时间】:2014-08-27 16:35:23
【问题描述】:
我的数据库中有以下结构:
-shared_resources 表 -标签表 -shared_resource_tag 表
shared_resources 和标签之间存在多对多的关系。当我创建一个 shared_resource 时,我会执行以下操作:
- 将 shared_resource 添加到 shared_resources 表中
- 将标签添加到标签表中
- 将 shared_resource_id 和 tag_id 添加到 shared_resource_tag 表中
我可以设法完成第 1 步和第 2 步,但由于某种原因,我无法在 pivot table 中输入任何内容。我不知道为什么。我相应地在models 中设置了关系:
SharedResource:
class SharedResource extends Eloquent{
public function tags(){
return $this->belongsToMany('Tag');
}
}
Tag:
class Tag extends Eloquent{
public function sharedResources(){
return $this->belongsToMany('SharedResource');
}
}
然后,当我创建条目时,我会这样做:
$tags = Array();
$tags = explode(',', Input::get('tags'));
foreach($tags as $tag){
$newTag = new Tag;
$newTag->name = $tag;
$newTag->save();
}
//Pivot table entry
$resource->tags()->sync($tags);
$resource->save();
上面的代码运行出错:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'shared_resource_id' in 'where clause' (SQL: select `tag_id` from `shared_resource_tag` where `shared_resource_id` is null)
我对发生的事情感到非常困惑,我知道Eloquent 使实现这些 n:n 关系变得容易。
【问题讨论】:
-
不是真的,否则我想我不会花时间把问题写出来......
-
那张桌子上有
shared_resource_id字段吗?
标签: mysql laravel laravel-4 many-to-many eloquent