user860511
user860511

Reputation:

Laravel - SELECT only certain columns within a `::with` controller function

The following code I have is working perfectly fine, however, it returns more data than what is necessary from each table:

public function getIndex()
    {
        $alerts = Criteria::with('bedrooms', 'properties')
        ->where('user_id', '=', Auth::id())
        ->get();

        $this->layout->content = View::make('users.alert.index', 
            array('alerts' => $alerts));
    }

What I'd like to do is, for example, select only the bedroom column out of the bedroom table. As it stands now, it returns all columns.

I have tried:

public function getIndex()
    {
        $alerts = Criteria::with('bedrooms' => function($q){
            $q->select('bedroom');
        }, 'properties')
        ->where('user_id', '=', Auth::id())
        ->get();

        $this->layout->content = View::make('users.alert.index', 
            array('alerts' => $alerts));
    }

But I am presented with the following error:

syntax error, unexpected '=>' (T_DOUBLE_ARROW)

Any help as to how I can achieve this will be hugely appreciated.


Update

public function getIndex()
{
    $alerts = Criteria::with(
        ['coordinate' => function($w){
            $w->select('name', 'id');
        }],
        ['bedrooms' => function($q){
            $q->select('bedroom', 'criteria_id');
        }]
        , 'properties')
    ->where('user_id', Auth::id())
    ->get();

    $this->layout->content = View::make('users.alert.index', 
        array('alerts' => $alerts));
}

The correct select query works for which ever is queried first. If I swap the queries around, the bedroom function works correctly, but the rest aren't eager loaded nor does the select query work.

Upvotes: 0

Views: 310

Answers (2)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81187

Just pass an array there:

// note [ and ]
$alerts = Criteria::with(['bedrooms' => function($q){
        $q->select('bedroom', 'PK / FK');
    }, 'properties'])

Also mind that you need to select the keys of that relation (primary key/foreign key of the relation).

Upvotes: 1

Sher Afgan
Sher Afgan

Reputation: 1234

The answer to your update question is that you need to eager load other values in the same array some thing like this.

public function getIndex()
{
    $alerts = Criteria::with(
        ['coordinate' => function($w)
        {
            $w->select('name', 'id');
        },
        'bedrooms' => function($q)
        {
            $q->select('bedroom', 'criteria_id');
        }
        , 'properties'])
    ->where('user_id', Auth::id())
    ->get();

    $this->layout->content = View::make('users.alert.index', 
        array('alerts' => $alerts));
}

Upvotes: 0

Related Questions