2014-06-19 44 views
-1

我是laravel和php的新手,我很難理解'關係'。(Laravel4)試圖打印出標籤

我想添加標籤到我的數據庫中的每個教程(這可能只是被視爲職位)。

當我嘗試打印出1個教程的所有標籤時,我只得到一個標籤,而我有2個標籤已分配給它。

控制器:

public function index() 
{ 
    $tags = Tutorial::where('id', '=', 1)->first()->tags()->get(); 
    //$tags = $tutorial->tags()->get(); 


    return View::make('home', array(
     'tags' => $tags 
    )); 
} 

教程模式:

class Tutorial extends Eloquent { 
    protected $table = 'tutorials'; 

    public function tags() { 
     return $this->belongsToMany('Tag', 'tutorials_tags', 'tag_id'); 
    } 
} 

標籤型號:

class Tag extends Eloquent { 
    protected $table = 'tags'; 
    public function Tutorials() { 
     return $this->belongsToMany('Tutorial', 'tutorials_tags', 'tutorial_id'); 
    } 
} 

查看:

@foreach($tags as $tags) 
    {{$tags->name}} 
@endforeach 

我的數據庫看起來是這樣的:

http://i.imgur.com/GIbqAGE.png

回答

1

我覺得你的循環導致,您正在使用的物品代替陣列與循環數組中的麻煩:

@foreach($tags as $tags) 
    {{$tags->name}} 
@endforeach 

嘗試將其更改爲:

@foreach($tags as $tag) 
    {{$tag->name}} 
@endforeach 

更新:另一個問題是您引用了錯誤的外鍵。

在許多一對多的關係,當您使用$this->belongsToMany(),即要求一個外鍵的第三個參數基本上是問:「數據透視表中的列,又名。tutorials_tags表,我應與此Tutorial模式? 」。當然應該是 tutorial_id

對於您的情況,當您在教程的tags()方法中指定tag_id時,它使Laravel認爲tag_id是您的教程ID,這是錯誤的。應該在數據透視表中查找Tutorial作爲tutorial_id

所以你public function tags()實際上需要是:

public function tags() { 
    return $this->belongsToMany('Tag', 'tutorials_tags', 'tutorial_id'); 
} 

或者作爲獎金點,如果你看一下Laravel的源代碼,它會做:

$foreignKey = $foreignKey ?: $this->getForeignKey(); 

而且getForeignKey()確實return snake_case(class_basename($this)).'_id';這,反過來,返回"tutorial_id"

既然你已經符合命名錶和外鍵的Laravel的標準,你可以省略像這樣的第三個參數:

public function tags() { 
    return $this->belongsToMany('Tag', 'tutorials_tags'); 
} 

這正好同其要求的「哪列$otherKey數據透視表,又名tutorials_tags表格,我應該與Tag模型匹配?「 所以它會是tag_id

所以我們用Tutorial模型完成。現在,我們來適用於Tag模型。所以在Tag模型應該是:

public function tutorials() { 
    return $this->belongsToMany('Tutorial', 'tutorials_tags', `tag_id`); 
} 
+0

不,它仍然只打印一個標籤,而我有2個標籤分配。 : - \ Thanks tho – Dieter91

+0

試試'$ this-> belongsToMany('Tag','tutorials_tags','tutorial_id');'或'$ this-> belongsToMany('Tag','tutorials_tags','tutorial_id','tag_id ');'在你的Tutorial :: tags()中。這就是http://laravel.com/docs/eloquent#many-to-many似乎暗示的。 – Unnawut

+0

大聲笑,那些都工作。我仍然不知道我在做什麼xD 謝謝 – Dieter91