从CategoryItems获取广告的类别 - Laravel 5.4

时间:2017-08-01 19:42:09

标签: php laravel laravel-5 laravel-5.4

您能否帮我从CategoryItems表中获取特定广告(帖子)的类别名称。

广告模型:

public function cat()
{
  return $this->belongsTo(Category::class);
}

public function categoryItems()
{
    return $this->hasMany(CategoryItems::class);
}

类别模型:

public function ads()
{
  return $this->hasMany(Ad::class);
}

public function categoryItems()
{
  return $this->hasMany(CategoryItems::class);
}

CategoryItems模型:

public function cat()
{
  return $this->belongsTo(Category::class);
}

public function ads()
{
  return $this->hasMany(Ad::class);
}

AdsController控制器:

public function show($slug)
{
  $ad = Ad::where('slug', $slug)->firstOrFail();
  $cat = Category::get();

  return view('ads.show', compact('ad', 'cat'));
}

查看:

<h2>{{ $ad->title }}</h2>
<div class="price">
  Price: {{ $ad->price }}
</div>
<div class="city">
  <h3>{{ $ad->city }}</h3>
</div>
<div class="cat">
  <h3>{{ $ad->categoryItems }}</h3>
</div>
<p>{{ $ad->body }}</p>
<p>Posted at: {{ $ad->created_at->toFormattedDateString() }}</p>

我现在在“猫”区块中得到的是:

[{"id":2,"category_id":5,"ad_id":4,"created_at":"2017-07-18 10:37:33","updated_at":"2017-07-18 10:37:33"}]

我还没有得到它......

更新

广告数据库:

id | title | slug | body | price | city | created_at | updated_at

类别DB:

id | title | slug | created_at | updated_at

CategoryItems DB:

id | category_id | ad_id | created_at | updated_at

1 个答案:

答案 0 :(得分:1)

实际上,每个广告都有几个类别项,因此您应该使用foreach。试试这个,看看是否能解决问题:

@foreach ($ad->categoryItems as $ci)
    <div class="cat">
        <h3>{{ $ci->cat->title }}</h3>
    </div>
@endforeach

并将ItemsCategory模型中cat()函数的代码更改为:

public function cat()
{
  return $this->belongsTo(Category::class, 'category_id');
}