这里是参考线: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
]
}
]
...
}
请提出可能是什么问题。
贵标签的模型有一个属性名为'tag'? – Jerodev
@Jerodev我已经用完整的'标记'模型更新了我的问题 – VLS