5

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.

Max Maximilian
  • 591
  • 2
  • 20

3 Answers3

4

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.

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
3

App\Posts::where will return a collection. So if you only want 1 result you should use App\Posts::where('display',1)->first()->contents

online Thomas
  • 8,864
  • 6
  • 44
  • 85
1

You need to call the first method before you call any relationship:

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

Or, if you want to fetch a collection of posts, you can:

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

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

Otherwise, you will just have a Query Builder object, without the actual results you want.

Luis Dalmolin
  • 3,416
  • 1
  • 18
  • 24