本文介紹了Laravel (HasMany) 不檢索值的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有以下型號:
namespace App;
use IlluminateDatabaseEloquentModel;
class forum_category extends Model
{
//
protected $table = 'forum_category';
public function posts()
{
$this->hasMany('Appforum_post');
}
}
和
namespace App;
use IlluminateDatabaseEloquentModel;
class forum_post extends Model
{
//
protected $table = 'forum_post';
public function category()
{
$this->belongsTo('Appforum_category');
}
}
在我的控制器中,我嘗試使用他們的帖子獲取所有類別:
in my controller i attempt to get all categories with their posts:
namespace AppHttpControllers;
use IlluminateHttpRequest;
use IlluminateRoutingController;
use Appforum_category as forum_category;
class ForumController extends Controller
{
public function __construct()
{
}
public function index ()
{
$categories = forum_category::all();
return view('forum', ['categories' => $categories]);
}
public function createPost()
{
}
public function createReply()
{
}
}
但是它似乎只返回我的類別.
However it seems to only be returning my categories.
誰能告訴我我做錯了什么?
Can someone tell me what ive done wrong?
推薦答案
查詢應如下所示:
$categories = forum_category::with('posts')->get();
https://laravel.com/docs/5.5/eloquent-relationships#eager-loading
如果您在 forum_post
表中有 category_id
,這將加載具有相關帖子的類別.
If you have category_id
in the forum_post
table, this will load categories with related posts.
然后只需遍歷集合以獲取帖子:
Then just iterate over the collection to get posts:
@foreach ($categories as $category)
@foreach ($category->posts as $post)
{{ $post->title }}
@endforeach
@endforeach
另外,關系應該是:
public function category()
{
return $this->belongsTo('Appforum_category');
}
這篇關于Laravel (HasMany) 不檢索值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!