Laravel:与父表上的 *where* 而不是 *find* 的雄辩关系

Max*_*ian 5 php laravel eloquent

我有一张桌子postsposts_contents。我只想从一篇帖子中获取内容,前提是该帖子具有display = 1.

(由于语言支持,我需要两个单独的表)

帖子:

id  user_id  display

1   2        0
2   2        1
3   2        0
4   2        1
Run Code Online (Sandbox Code Playgroud)

帖子内容

id  post_id  lang_id  name    description

1   1        1        Hello   World
2   2        1        Here    Is What I wanna show!
3   3        1        Don't   Show the others
4   4        1        Hey     Display that one too
Run Code Online (Sandbox Code Playgroud)

所以在 Laravel 中我使用雄辩的关系,但我只是不明白如何在特定情况下使用它。在文档中我只发现了以下情况:

$p = App\Posts::find(1)->contents;
Run Code Online (Sandbox Code Playgroud)

效果很好,但我想要的是这样的:

$p = App\Posts::where('display',1)->contents;
Run Code Online (Sandbox Code Playgroud)

但这不起作用......所以问题是:正确的方法是什么?

感谢任何帮助,谢谢!

更新

我需要一次获得多个帖子,而不仅仅是一个。

Ale*_*nin 4

你想使用find()这样的方法:

$post = App\Posts::where('display', 1)->find($postId)->contents;
Run Code Online (Sandbox Code Playgroud)

然后在一对一关系的视图中:

{{ $post->description }}
Run Code Online (Sandbox Code Playgroud)

对于一对多:

@foreach ($post->contents as $content)
    {{ $content->description }}
@endforeach
Run Code Online (Sandbox Code Playgroud)

如果您想加载仅包含一种语言内容的多个帖子,请使用按语言过滤。用于with()急切加载内容:

$posts = App\Posts::where('display', 1)
    ->with(['contents' => function($q) use($langId) {
        $q->where('lang_id', $langId);
    }])
    ->get();
Run Code Online (Sandbox Code Playgroud)

然后在一对一的视图中:

@foreach ($posts as $post)
    {{ $post->contents->description }}
@endforeach
Run Code Online (Sandbox Code Playgroud)

对于一对多:

@foreach ($posts as $post)
    @foreach ($post->contents as $content)
        {{ $content->description }}
    @endforeach
@endforeach
Run Code Online (Sandbox Code Playgroud)

您可以在此处find()了解和get()方法之间的区别。