我的查詢是:$posts = Post:: whereIn('ID', ( NewsTag:: orderBy('post_date','desc')->with('publisher','newsTopics') ->paginate(12)->pluck('post_id'))) ->get();Newstag.php 模型是這樣的: public function newsTopics() { return $this->hasOne('App\Models\NewsTopics', 'post_id', 'post_id'); } public function publisher() { return $this->hasOne('App\Models\Publisher', 'id', 'publisher_id'); } 當我執行以下操作時,我無法訪問 publisher 和 newsTopics:@foreach($posts as $post)//doesn't work this way$post->publisher->name;//nor like this$publisher->name;我怎樣才能訪問發布者和新聞主題?當我運行這個控制器時,它會查詢我想要的內容,但我無權訪問它。任何幫助,將不勝感激。謝謝你!
1 回答

撒科打諢
TA貢獻1934條經驗 獲得超2個贊
為了獲得模型關系,您必須先在查詢中加載它們:
$posts = Post::with('newsTopics','publisher')->
? ? whereIn('ID', (
? ? NewsTag::
? ? ? ? ? ? ?orderBy('post_date','desc')->with('publisher','newsTopics')
? ? ? ? ? ? ? ? ?->paginate(12)->pluck('post_id')))
? ? ? ? ? ? ?->get();
然后你可以像這樣訪問你的關系:
@foreach($posts as $post)
$publisherName= $post->publisher->name;
- 1 回答
- 0 關注
- 102 瀏覽
添加回答
舉報
0/150
提交
取消