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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?