Laravel - 仅选择`:: with`控制器函数中的某些列

时间:2015-01-08 13:52:28

标签: select laravel laravel-4 eloquent

以下代码工作正常,但是,它返回的数据多于每个表所需的数据:

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));
    }

我想做的是,例如,只选择bedroom表格中的bedroom列。就像现在一样,它返回所有列。

我试过了:

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));
    }

但我收到以下错误:

  

语法错误,意外'=>' (T_DOUBLE_ARROW)

任何有关如何实现这一目标的帮助都将受到极大的赞赏。


更新

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));
}

正确的select查询适用于首先查询的查询。如果我交换查询,bedroom函数可以正常工作,但其余部分不会急切加载,select查询也无效。

2 个答案:

答案 0 :(得分:1)

只需在那里传递数组:

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

还要注意你需要选择该关系的密钥(关系的主键/外键)。

答案 1 :(得分:0)

更新问题的答案是,您需要在同一个数组中加载其他值,例如:

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));
}
相关问题