使用Eloquent实现Laravel 4数据透视表

时间:2014-08-27 16:35:23

标签: mysql laravel laravel-4 many-to-many eloquent

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

-shared_resources表 -tags表 -shared_resource_tag表

shared_resources和tags之间有很多关系。当我创建shared_resource时,我会执行以下操作:

  1. 将shared_resource添加到shared_resources表
  2. 将标签添加到标签表
  3. 将shared_resource_id和tag_id添加到shared_resource_tag表
  4. 我可以设法完成第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关系。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

    $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 );