drtsd7864 2017-01-25 12:40
浏览 53
已采纳

数据不是来自laravel关系中的2个表+ 1个数据透视表

Here is the thread for reference: Simple tags system in Laravel 5.2

I can't make those tags displayed on the page. It's always return null here is the source I have:

Item model

public function tags() {

    return $this->belongsToMany('App\Tag', 'item_tag');
}

Tag model

class Tag extends Model {

    protected $table = 'tags';
    protected $primaryKey = 'id';

    protected $fillable = [
        'tag'
    ];

    public function itemTags() {

        return $this->belongsToMany('App\Item', 'item_tag');

    }    

}  

ItemController

public function show($id)
{
     $item = Item::with('tags')->find($id);
     return view('item', compact('item'));
}

And the view

@foreach($item->tags() as $showTags)         
      {{ $showTags->tag }}                  
@endforeach 

dd($item) return two tags in relation so I assume they are there in collection but the return is either empty space on the page or null.

Item {#322 ▼
  #primaryKey: "id"
  #table: "items"
  #fillable: array:9 [▶]
  #connection: null
  #keyType: "int"
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: array:25 [▶]
  #original: array:25 [▶]
  #relations: array:1 [▼
    "tags" => Collection {#332 ▼
      #items: array:2 [▼
        0 => Tag {#330 ▶}  // tag 1
        1 => Tag {#331 ▶}  // tag 2
      ]
    }
  ]
   ...
}

Please suggest what can be the problem.

  • 写回答

1条回答 默认 最新

  • duanlei0282 2017-01-25 12:50
    关注

    After eager loading you don't need to invoke the relationship, its available as a collection:

    // $item->tags not $item->tags() since its a collection
    @foreach($item->tags as $showTags)         
          {{ $showTags->tag }}                  
    @endforeach 
    
    // if you don'nt eager load, then you can call the relationship
    @foreach($item->tags()->get() as $showTags)
    ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用