【发布时间】: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 绝对不是。如果您没有加载用户,那么它将运行冗余查询,而如果您只需要
id,Auth::id()是要走的路。 -
@JarekTkaczyk 好提示,谢谢
标签: select laravel laravel-4 eloquent