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 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面