Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Eloquent relationships with *where* on parent table instead of *find*

I have a table posts and posts_contents. And I want to get a content from one post only if that post has display = 1.

(I need two separate tables because of 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 eloquent relationships, but I just don't understand how to use it in that particular case. In the documentation I found only cases such as:

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

Which works great, however what I want is something like this:

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

But it doesn't work... So question is: what is the right way to do so?

Any help is appreciated, Thanks!

Update

I need to get multiple posts at once, not just one.

like image 752
Max Maximilian Avatar asked Jan 29 '23 17:01

Max Maximilian


1 Answers

You want to use find() method like this:

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

Then in a view for one-to-one relationship:

{{ $post->description }}

For one-to-many:

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

If you want to load multiple posts with contents only for one language, use filtering by a language. Use with() to eager load contents:

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

Then in a view for one-to-one:

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

For one-to-many:

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

You can read about the difference between find() and get() methods here.

like image 106
Alexey Mezenin Avatar answered Jan 31 '23 09:01

Alexey Mezenin