2017-01-25 94 views
0

这里是参考线:Simple tags system in Laravel 5.2数据未从2个表+ 1的数据透视表进来laravel关系

我不能使页面上显示这些标签。它总是返回null这里是我源:

项目模型

public function tags() { 

    return $this->belongsToMany('App\Tag', 'item_tag'); 
} 

标签模型

class Tag extends Model { 

    protected $table = 'tags'; 
    protected $primaryKey = 'id'; 

    protected $fillable = [ 
     'tag' 
    ]; 

    public function itemTags() { 

     return $this->belongsToMany('App\Item', 'item_tag'); 

    }  

} 

ItemController

public function show($id) 
{ 
    $item = Item::with('tags')->find($id); 
    return view('item', compact('item')); 
} 

和视图

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

dd($item)返回关系中的两个标签,所以我假设他们在收集中,但返回或者是页面上的空白空间或null

Item {#322 ▼ 
    #primaryKey: "id" 
    #table: "items" 
    #fillable: array:9 [▶] 
    #connection: null 
    #keyType: "int" 
    #perPage: 15 
    +incrementing: true 
    +timestamps: true 
    #attributes: array:25 [▶] 
    #original: array:25 [▶] 
    #relations: array:1 [▼ 
    "tags" => Collection {#332 ▼ 
     #items: array:2 [▼ 
     0 => Tag {#330 ▶} // tag 1 
     1 => Tag {#331 ▶} // tag 2 
     ] 
    } 
    ] 
    ... 
} 

请提出可能是什么问题。

+0

贵标签的模型有一个属性名为'tag'? – Jerodev

+0

@Jerodev我已经用完整的'标记'模型更新了我的问题 – VLS

回答

1

预先加载后,您不需要调用关系,其作为收藏品可供选择:

// $item->tags not $item->tags() since its a collection 
@foreach($item->tags as $showTags)   
     {{ $showTags->tag }}     
@endforeach 

// if you don'nt eager load, then you can call the relationship 
@foreach($item->tags()->get() as $showTags) 
... 
+0

嗯,我已经尝试了很多次,并没有工作,因为我总是得到'为foreach()提供了无效参数'我改变了名字模型中的函数转换为'taggs',而不是使用'$ item-> taggs' ..在这个单词'tag'中有什么特别的,这就是为什么导致这个问题的原因? – VLS

+0

@VLS不,标签不是保留关键字。你尝试过第二种方法吗?不急于加载? –

+0

是的,第二种方法工作正常。正当我尝试'$ item-> tags()'show empty/null和'$ item-> tags'显示'无效参数...'时。我很奇怪。 – VLS