Laravel关系不会返回任何内容

问题描述 投票:1回答:4

我在laravel雄辩的关系中有问题。我的应用程序中有2个模型:文章和类别。

文章模型:

public function category()
{
    return $this->belongsToMany('App\Category');
}

类别模型:

public function article()
{
    return $this->hasMany('App\Article');
}

此束之间的关系为hasMany (Category -> article)belongsToMany (Article -> category)

类别将使用categoryController的此方法按请求的段获取:

$category = Category::where('slug', '=', $slug)->get();

当我想从类别中获取文章时,问题将显示在视图中,什么也不会返回:

@foreach ($category->article->all() as $article)
    {{ $article->name }}
@endforeach

并且从@dd($category->article)中我们将获得空集合:

Collection {#323 ▼
  #items: []
}
php laravel eloquent
4个回答
0
投票

您可以使用@forelse刀片指令,如

@forelse ($category->article as $article)
    <li>{{ $article->name }}</li>
@empty
    <p>No articles</p>
@endforelse

您可以检查here


0
投票

更改如下

@foreach ($category->article as $article)
    {{ $article->name }}
@endforeach

也可以在查询中使用with()

$category = Category::with('article')->where('slug', '=', $slug)->get();

参考:https://laravel.com/docs/5.8/eloquent-relationships#eager-loading


0
投票

您不需要写$category->article->all()$category->article本身将返回所有文章。因此,只需使用,

@foreach ($category->article->all() as $article)
  {{ $article->name }}
@endforeach

对于渴望加载文章,您可以使用[with关键字

$category = Category::with('article')->where('slug', '=', $slug)->get();

-1
投票

在您的控制器中

$category = Category::with('article')->where('slug',$slug)->get();

在blade.php文件中

@foreach($category->article as $article)
    <li>{{ $article->name }}</li>
@endforeach
© www.soinside.com 2019 - 2024. All rights reserved.