Laravel - 选择/加入朋友到帖子表

时间:2018-06-12 04:34:50

标签: laravel

我对laravel和SQL语句都很陌生,我试图让帖子显示或加载登录用户和他的朋友的帖子。 posts表有一个author_id,friends表有sender / recipient / status 发件人或收件人可以是当前登录的人,状态是2(已接受) 目前我有这个

@foreach(Friends::where("sender", "=", Auth::user()->id)->orWhere("recipient", "=", Auth::user()->id)->where("status", "=", 2)->get() as $friend)
@foreach(Posts::where("author_id", "=", Auth::user()->id)->orWhere("author_id", "=", $friend->recipient)->where("relation", "=", "feed")->orderBy('post_time', 'DESC')->orderBy('post_date', 'DESC')->get() as $post)

有人可以告诉我或告诉我如何加入帖子/朋友,并有一个循环显示我和朋友帐户的内容。

2 个答案:

答案 0 :(得分:0)

我希望这可以提供帮助

@php

$friendsPosts = Friends::where("sender", "=", Auth::user()->id)
                    ->orWhere("recipient", "=", Auth::user()
                    ->id)->where("status", "=", 2)
                    ->with([ 'posts' => function ($query) {
                        $query->where("relation", "=", "feed")
                            ->orderBy('post_time', 'DESC')
                            ->orderBy('post_date', 'DESC');
                    }])->get();
                            
@endphp

@foreach ($friendsPosts as $post)

<!-- code inside the loop -->

@endforeach

答案 1 :(得分:0)

我会继续@tirta的回答,请确认你确实有一个名为&#39; posts&#39;在朋友&#39;模型由此建立了Friends.php&#39;之间的关系。和&#39; Posts.php&#39;。