A
A
Abc Edc2015-10-19 16:27:09
Laravel
Abc Edc, 2015-10-19 16:27:09

How to specify the required fields in relations?

Tried many ways and none of them worked.

News::query();
        if ($request->has('is_hidden')) {
            $query->where('is_hidden', 1);
        }
        if ($request->has('is_moderated'))
            $query->where('is_moderated', 1);
        $list = $query->with(array('source' => function ($query) {
            $query->select(['id', 'url', 'name']);
        }))->select(['id', 'image_url', 'published', 'added', 'header']);

So in source-null
News::query();
        if ($request->has('is_hidden')) {
            $query->where('is_hidden', 1);
        }
        if ($request->has('is_moderated'))
            $query->where('is_moderated', 1);
        $list = $query->with(array('source' => function ($query) {
            $query->get(['id', 'url', 'name']);
        }))->get(['id', 'image_url', 'published', 'added', 'header'])

And so too
if ($request->has('is_hidden')) {
            $query->where('is_hidden', 1);
        }
        if ($request->has('is_moderated'))
            $query->where('is_moderated', 1);
        $list = $query->with('source')->get();

That's not null, but here I didn't specify the fields, how to make sure that the fields can be specified both in source and news

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
D', 2015-10-19
@gleber1

Common problem. Solved by adding the key to the select list :

$list = $query->with(array('source' => function ($query) {
    $query->select(['id', 'url', 'name', 'key_field']);
}))->select(['id', 'image_url', 'published', 'added', 'header']);

Where key_field is the field that you have linking the News and Source tables. For example news_id, or whatever you call it there.

V
Vyacheslav Plisko, 2015-10-19
@AmdY

You have a small error in the first option, you don't need to pass an array to select, but just fields separated by commas

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question