【问题标题】:Laravel - SELECT only certain columns within a `::with` controller functionLaravel - 仅选择`::with`控制器函数中的某些列
【发布时间】:2015-01-08 13:52:27
【问题描述】:

我的以下代码运行良好,但是,它返回的数据比每个表所需的数据多:

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 查询也不会工作。

【问题讨论】:

  • 请注意,您可能想使用Auth::user()->id 而不是Auth::id() 来获取当前用户的ID。
  • @msturdy,注意到并更改了。非常感谢。
  • @msturdy 绝对不是。如果您没有加载用户,那么它将运行冗余查询,而如果您只需要 idAuth::id() 是要走的路。
  • @JarekTkaczyk 好提示,谢谢

标签: select laravel laravel-4 eloquent


【解决方案1】:

只需在此处传递一个数组:

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

另外请注意,您需要选择该关系的键(关系的主键/外键)。

【讨论】:

  • 这是否适用于with 函数中的多个表?我已经向properties 添加了一个查询,但它似乎仍在选择所有列。此外,其他表的急切加载似乎已经消失?
  • 请查看更新的部分@Jarek,当我将函数添加到多个表时,它似乎不起作用。
  • 是的,右括号放错了位置。您需要传递具有多个键/闭包的单个数组。检查编辑。
【解决方案2】:

更新问题的答案是,您需要像这样急切地在同一个数组中加载其他值。

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

【讨论】:

    猜你喜欢
    • 2020-10-15
    • 1970-01-01
    • 2017-03-23
    • 2019-04-18
    • 1970-01-01
    • 1970-01-01
    • 2012-08-08
    • 1970-01-01
    • 2014-09-21
    相关资源
    最近更新 更多