gpt4 book ai didi

php - Laravel 5.3 中为 foreach() 提供的参数无效

转载 作者:行者123 更新时间:2023-11-29 19:43:14 25 4
gpt4 key购买 nike

我不知道它到底是如何工作的,所以这就是我问的原因。我仍在开发公告板系统,现在我希望在每个类别下都有一个子类别

例如: enter image description here

我在 LaraCasts 上使用以下线程完成了此操作: https://laracasts.com/discuss/channels/eloquent/eloquent-getting-subcategories-from-the-categories

现在我的 IndexController 看起来像这样:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Thread;
use App\Chat;
use App\Category;


class IndexController extends Controller
{
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$threads = Thread::all()->toArray();
$chats = Chat::orderBy('id', 'DESC')->take(50)->with('author')->get();
$categories = Category::with('sub_category')->get();

return view('index', compact('threads','chats','categories'));
}

}

这是我的类别模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{


public function sub_category()
{
return $this->belongsTo(self::class, 'parent_id', 'id');
}

public function parent_category()
{
return $this->hasMany(self::class, 'id', 'parent_id');
}


}

我的观点(index.blade.php):

  @foreach($categories as $category)
<div class="col-md-8">
<div class="panel panel-primary">
<div class="panel-heading"><i class="fa fa-angle-right" aria-hidden="true"></i> {{ $category->caption }}</div>
<div class="panel-body">



@foreach($category->sub_category as $sub_category)

<div class="row forum-row">

<div class="col-xs-12 col-md-8 col-sm-8">

<div class="hidden-xs visible-sm visible-lg visible-md pull-left forum-icon-read">
<i class="fa fa-comment"></i>
</div>
<a href="#">{{ $sub_category->caption }}</a><br>
<small>{{ $sub_category->desc }}</small>

</div>

<div class="col-xs-12 col-md-4 col-sm-4 forum-latest-container">
<p class="forum-data cutoff"><a href="#">Test</a></p>
<small>
door <a class="Donateur" href="/user-Sygun">Sygun</a>
<p class="forum-data">
2 minuten geleden </p>
</small>
</div>

</div>
@endforeach


</div>
</div>
</div>
@endforeach

我还有两个数据库表:

  • 子类别(id、标题、parent_id、min_rank、desc)

  • 类别(id、标题、min_rank、desc)

我收到的错误消息:

Invalid argument supplied for foreach()

你能告诉我实现这一目标的正确方法是什么吗?

最佳答案

创建两个名为CategorySubCategory的模型。

在类别模型中

public function subcategories()
{
return $this->hasMany('App\SubCategory', 'parent_id');
}

在子类别模型中

public function parent_category()
{
return $this->belongsTo('App\Category', 'parent_id');
}

然后在你的 Controller 中查询它,如下所示:

$categories = Category::with('subcategories')->get();

希望您的 foreach 能够正常工作。

关于php - Laravel 5.3 中为 foreach() 提供的参数无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41209562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com