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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀