以下是供引用的线程:Simple tags system in Laravel 5.2
我无法让这些标签显示在页面上。它总是返回 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');
}
}
项目 Controller
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
]
}
]
...
}
请提出可能出现的问题。
最佳答案
急切加载后,您不需要调用关系,它可以作为集合使用:
// $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)
...
关于php - 数据不是来自 Laravel 关系中的 2 个表 + 1 个数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41851900/