我需要帮助,查询模型关系时遇到问题 . 我实际上知道并使用查询方法完成工作,但我想知道查询关系的“laravel方式” .
这是我控制器上的内容 . // HealthProfile Controller // $ id值为2
$health_profiles = User::find($id)->with('health_profiles')->first();
问题是查询的返回值是id = 1而不是id = 2的记录 . 它基本上忽略了“find”方法 . 我只想获取特定user_id的 Health 配置文件 .
[id] => 1
[firstname] => patrick
[lastname] => marino
[email] => patrick@gmail.com
[membership_code] => starpatrick
[birthdate] => 1989-05-17
[contact_number] => 1230123
[active] => 1
[created_at] => 2014-07-01 16:10:05
[updated_at] => 2014-07-01 16:10:05
[remember_token] =>
[health_profiles] => Array
(
[0] => Array
(
[id] => 1
[user_id] => 1
[parent_id] =>
[name] => patrick star
[relationship] =>
[gender] => male
[birthdate] => 1989-05-17
[marital_status] =>
[number_of_children] =>
[weigth] =>
[height] =>
[blood_type] =>
[blood_pressure] =>
[hdl] =>
[ldl] =>
[vldl] =>
[visual_activity] =>
[lifestyle] =>
[current_bmi] =>
[weight_goal] =>
[weekly_goal] =>
[rdc] =>
[created_at] => 2014-07-01 16:10:05
[updated_at] => 2014-07-01 16:10:05
)
这是我的架构//用户模型
public function health_profiles()
{
return $this->hasMany('HealthProfile');
}
// HealthProfile模型
public function user()
{
return $this->belongsTo('User', 'user_id', 'id');
}
4 回答
试试这个
我认为您不需要调用
first
方法,因为find
因为它所声明的只会找到您需要的一行数据 .您可以尝试在
find
之前放置with
,以便构建器知道在您尝试查找的内容上急切加载该关系 .我找到了罪魁祸首 . L4有蛇套方法的问题!我将它更改为camelCase并且它有效 .
src:https://coderwall.com/p/xjomzg
首先说几句:
find($id)
已经运行了查询(它在引擎盖下使用了where(id, $id)->first()
),所以把它放在最后,因为现在你不知不觉地这样做了:另一个问题是,就像您已经注意到的那样,
Eloquent
将无法使用此设置:因为在加载动态属性(关系)时,它会在模型上查找camelCased方法 .
然而,急切加载 will 按预期工作:
所以如果你想
Eloquent
成为你的朋友,你肯定应该遵守命名约定;)But that's not all. It will work the other way around:
To sum up and answer your question ,每个都适合你: