【问题标题】:Implementing a Laravel 4 Pivot Table using Eloquent使用 Eloquent 实现 Laravel 4 数据透视表
【发布时间】:2014-08-27 16:35:23
【问题描述】:

我的数据库中有以下结构:

-shared_resources 表 -标签表 -shared_resource_tag 表

shared_resources 和标签之间存在多对多的关系。当我创建一个 shared_resource 时,我会执行以下操作:

  1. 将 shared_resource 添加到 shared_resources 表中
  2. 将标签添加到标签表中
  3. 将 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


【解决方案1】:

sync() 方法需要标签的 id,而不是您提供的字符串名称。您可以尝试以下方法:

$tags = Array();
$tagIds = Array();
$tags = explode(',', Input::get('tags'));
foreach($tags as $tag){
    $newTag = new Tag;
    $newTag->name = $tag;
    $newTag->save();
    $tagIds[] = $newTag->id;
}

//Pivot table entry
$resource->tags()->sync($tagIds);

$resource->save();

您可以在Using Sync To Attach Many To Many Models 下找到更多信息here

【讨论】:

  • 我明白你在说什么@Chris G,尽管关于Column not found: 1054 Unknown column 'shared_resource_id,我仍然收到错误消息,我尝试在进行数据透视条目之前保存资源,但没有奏效
  • @Javacadabra - 您可能必须添加要加入的列名:return $this->belongsToMany('SharedResource');。来自手册:return $this->belongsToMany('Role', 'user_roles', 'user_id', 'foo_id'); 看起来 Laravel 正在尝试建立一个不存在的连接(鉴于缺少的列),因此您必须在模型中强制它们覆盖默认操作。
【解决方案2】:
    $tags = explode(',', Input::get('tags'));
    // Create or add tags
    $tagIds = array();

    if ( $tags )
    {
        $found = $this->tag->findOrCreate( $tags );
        foreach ( $found as $tag )
        {
            $tagIds[ ] = $tag->id;
        }
    }

    // Assign set tags to model
    $model->tags()->sync( $tagIds );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 2018-11-11
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多