【问题标题】:Laravel - Select / join friends to posts tableLaravel - 选择/加入朋友到帖子表
【发布时间】:2018-11-21 09:17:18
【问题描述】:

我对 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)

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

【问题讨论】:

  • 这个逻辑应该隐藏在模型内部的一个方法后面,我建议使用 Eloquent 关系来处理这个问题。您可以在这里制作一些映射,一对多用于用户关系,然后一对多用于用户帖子

标签: laravel


【解决方案1】:

希望对你有帮助

@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

【讨论】:

  • 嗨,我试过了,虽然遇到了这个Call to undefined method Illuminate\Database\Query\Builder::Posts() (View: /var/www/dev-facesmash/app/views/home.blade.php)
【解决方案2】:

我会继续@tirta 的回答,请确认您在“Friends”模型中确实有一个名为“posts”的关系,从而在“Friends.php”和“Posts.php”之间建立了一个关系。

【讨论】:

    猜你喜欢
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多