doujianchao7446 2016-05-18 07:53
浏览 16
已采纳

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

I have this code snippet in my 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

In $product->tags ( tags is the name of my relation ) are the tags I need and some other things, but I only want the tags.

I tried to reach them with $product->tags->tag but this hasn't worked for me. Can anybody tell me how I can access only the tags?

  • 写回答

2条回答 默认 最新

  • ds342222 2016-05-18 08:25
    关注

    If you have a relationship set between your Products and it's Tags (https://laravel.com/docs/5.1/eloquent-relationships)

    Products Model

    //namespace and use statements
    class Products extends Model
    {
        /**
         * Get all of the tags for the product.
         */
        public function tags()
        {
            return $this->hasMany('App\Tags');
        }
    }
    

    Tags Model (assuming tags can be used for multiple products)

    //namespace and use statements
    class Tags extends Model
    {
        /**
          * The tags that belong to the product.
          */
        public function products()
        {
            return $this->belongsToMany('App\Products');
        }
    }
    

    Then you can query in you controller for the products with their tags (https://laravel.com/docs/5.1/eloquent-relationships#querying-relations)

    $products = App\Products::with('tags')->get();
    

    Then you can simply access them in your view with your current code but using

    @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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?