我的刀片中有以下代码片段:
@foreach($products as $product)
<tr>
<td></td>
<td>{{ $product->name }}</td>
<td>{{$product->tags}}</td>
<td>{{$product->created_at}}</td>
<td>
// some other code and buttons
</td>
</tr>
@endforeach
在$product->标签(标签是我关系的名称(中,是我需要的标签和其他一些东西,但我只想要标签。
我试图用$product->标签->标签与他们联系,但这对我不起作用。谁能告诉我如何只访问标签?
试试这个:
@foreach($product->tags as $tag)
<td>{{ $tag->tag }}</td>
@endforeach
$product->tags
return
Tag
对象的array
。
如果你的Products
和它之间设置了关系Tags
(https://laravel.com/docs/5.1/eloquent-relationships(
产品型号
//namespace and use statements
class Products extends Model
{
/**
* Get all of the tags for the product.
*/
public function tags()
{
return $this->hasMany('App'Tags');
}
}
标签模型(假设标签可用于多个产品(
//namespace and use statements
class Tags extends Model
{
/**
* The tags that belong to the product.
*/
public function products()
{
return $this->belongsToMany('App'Products');
}
}
然后,您可以在控制器中查询带有标签的产品(https://laravel.com/docs/5.1/eloquent-relationships#querying-relations(
$products = App'Products::with('tags')->get();
然后,您可以使用当前代码在视图中简单地访问它们,但使用
@foreach($products as $product)
<tr>
<td></td>
<td>{{ $product->name }}</td>
@foreach($product->tags as $tag)
<td>{{ $tag->name }}</td>
@endforeach
<td>{{ $product->created_at }}</td>
<td>
// some other code and buttons
</td>
</tr>
@endforeach