Laravel: Vivid relationship with * where * on the parent table instead of * find *

I have a table postsand posts_contents. And I want to get content from one message only if this message has it display = 1.

(I need two separate tables due to language support)

posts:

id  user_id  display

1   2        0
2   2        1
3   2        0
4   2        1

posts_contents

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

So, in laravel I use an eloquent relationship, but I just don’t understand how to use it in this particular case. In the documentation, I found only such cases as:

$p = App\Posts::find(1)->contents;

Which works fine, however I want something like this:

$p = App\Posts::where('display',1)->contents;

But that will not work ... The question is, is this the right way to do this?

Any help is appreciated, thanks!

Update

I need to receive several messages at once, and not just one.

+4
source share
3

find() :

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

- :

{{ $post->description }}

--:

@foreach ($post->contents as $content)
    {{ $content->description }}
@endforeach

, . with() :

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

" ":

@foreach ($posts as $post)
    {{ $post->contents->description }}
@endforeach

--:

@foreach ($posts as $post)
    @foreach ($post->contents as $content)
        {{ $content->description }}
    @endforeach
@endforeach

find() get() .

+4

App\Posts::where . , 1 , App\Posts::where('display',1)->first()->contents

+2

first, - :

$p = App\Posts::where('display', 1)->first()->contents;

, , :

$posts = App\Posts::where('display', 1)->get();

$posts->each(function ($post) {
    $post->contents;
});

Query Builder , .

+1
source

Source: https://habr.com/ru/post/1693365/


All Articles