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

时间:2016-05-18 07:53:28

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

我尝试使用$ product-&gt; tags-&gt;标记与他们联系,但这对我没用。谁能告诉我如何才能访问标签?

2 个答案:

答案 0 :(得分:3)

试试这个:

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

$product->tags return arrayTag个对象。

答案 1 :(得分:2)

如果您在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
相关问题