我使用Laravel Eloquent模型对这些表进行建模:
用户:id
firstName
lastName
password
email
帖子:id
user_id
title
content
发布模型,其关系为hasOne
('User'
)和用户模型,具有计算属性:
protected $appends = ['name'];
public function getNameAttribute(){
return $this->attributes['name'] = $this->firstName.' '. $this->lastName;
}
我需要使用预先加载来获取帖子的作者姓名,而不是用户表中的所有列。
我试过了:
$result = Post::with(
[
'user' => function( $query ){
$query->select('name');
}
]
)->get();
但显然name
不是表格中的列,而只是计算属性。那我怎么能这样做呢?
答案 0 :(得分:1)
您无法在查询中使用访问者。你有两个选择:
选项一:在查询中复制您的访问者逻辑:
$result = Post::with(
[
'user' => function( $query ){
$query->selectRaw("id, CONCAT_WS(' ', firstName, lastName) as name");
}
]
)->get();
print_r($result->first()->user->name);
由于您的名称属性现在来自查询,因此您还需要修改访问者以使用现有值(如果已存在):
public function getNameAttribute($value = null) {
$name = $value ?: $this->firstName.' '.$this->lastName;
return $this->attributes['name'] = $name;
}
选项二:只需确保选择访问者所需的所有字段:
$result = Post::with(
[
'user' => function( $query ){
$query->select('id, firstName, lastName');
}
]
)->get();
print_r($result->first()->user->name);