从 blade 中的关系访问数据? - Laravel

Accessing data from a relation in blade? - Laravel

我的 blade 中有这个代码片段:

 @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->tags(tags 是我关系的名称)中是我需要的标签和其他一些东西,但我想要标签。

我尝试使用 $product->tags->tag 联系他们,但这对我不起作用。谁能告诉我如何才能只访问标签?

试试这个:

@foreach($product->tags as $tag)
   <td>{{ $tag->tag }}</td>
@endforeach

$product->tags return arrayTag 个对象。

如果您在 ProductsTags (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