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

标签 php mysql laravel

以下是供引用的线程:Simple tags system in Laravel 5.2

我无法让这些标签显示在页面上。它总是返回 null 这是我的来源:

商品型号

public function tags() {

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

标签模型

class Tag extends Model {

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

    protected $fillable = [
        'tag'
    ];

    public function itemTags() {

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

    }    

}  

项目 Controller

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

还有景色

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

dd($item) 返回两个相关标签,因此我假设它们在集合中,但返回的要么是页面上的空白空间,要么是 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
      ]
    }
  ]
   ...
}

请提出可能出现的问题。

最佳答案

急切加载后,您不需要调用关系,它可以作为集合使用:

// $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)
...

关于php - 数据不是来自 Laravel 关系中的 2 个表 + 1 个数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41851900/

相关文章:

php - 在 PHP 中发送之前压缩一个 JSON 对象

mysql - 如何将两个不同的ID连接到另一个表中?

Laravel Blade 模板 - 如何在 foreach 循环中使用增量变量

php - 在购物车中保存产品自定义字段值并将其显示在购物车和结帐中

php - 删除/删除 laravel 项目

java - 使用 HIbernate 从数据库检索日期时获取错误的日期时间字段值

mysql - 按仅包含特定日期的日期分组

php - 从 Laravel Routes.php 调用 Controller 函数

php - 调用 php artisan db :seed does not work without providing a class name

php - Php:如何将URL与以HTML部分为目标的ID链接?