我想在laravel eager loading中使用别名。这是我的查询
Message::whereIn('conversation_id',$msgs)
->where('deleted', '!=', $userId)
->with(array('last_sender' =>function($query) use ($userId){
$query->where('id','!=', $userId);
$query->select('id', 'userName', 'profilePic','firstName', 'lastName');
}))
->with(array('last_reciever' =>function($query) use ($userId){
$query->where('id','!=', $userId);
$query->select('id', 'userName', 'profilePic','firstName', 'lastName');
}))
->orderBy('conversation_id', 'desc')
->orderBy('id', 'desc')
->groupBy('conversation_id')
->get();
此查询返回用户对象,因为last_sender
和last_reciever
保持为空或last_reciever
且last_sender
保持为空。
这是此查询返回的结果对象
{
"data": [
{
"id": 85,
"conversation_id": 18,
"last_reciever": null,
"last_sender": {
"id": 39,
"userName": "df76236sd",
"profilePic": "aFHZmeMHQ6nd3Ll3nzCqYEw2CTBsun3f1hxm3yKc.jpeg",
"firstName": "sadek ",
"lastName": "sdfsd"
},
"msg": "abe sala",
"attachment": null,
"deleted": 0,
"seen": 0,
"created_at": "2017-08-19 02:24:05",
"updated_at": "2017-08-19 02:24:05"
},
{
"id": 80,
"conversation_id": 16,
"last_reciever": {
"id": 39,
"userName": "df76236sd",
"profilePic": "aFHZmeMHQ6nd3Ll3nzCqYEw2CTBsun3f1hxm3yKc.jpeg",
"firstName": "sadek ",
"lastName": "sdfsd"
},
"last_sender": null,
"msg": "now should be working just fine",
"attachment": null,
"deleted": 0,
"seen": 1,
"created_at": "2017-08-19 02:19:34",
"updated_at": "2017-08-19 02:19:34"
}
]
}
我要做的是用自定义名称last_sender
替换last_reciever
和oponent
。为此我尝试使用类似的东西
Message::whereIn('conversation_id',$msgs)
->where('deleted', '!=', $userId)
->with(array('last_sender as oponent' =>function($query) use ($userId){
$query->where('id','!=', $userId);
$query->select('id', 'userName', 'profilePic','firstName', 'lastName');
}))
->with(array('last_reciever as oponent' =>function($query) use ($userId){
$query->where('id','!=', $userId);
$query->select('id', 'userName', 'profilePic','firstName', 'lastName');
}))
->orderBy('conversation_id', 'desc')
->orderBy('id', 'desc')
->groupBy('conversation_id')
->get();
它不起作用。有没有其他方法可以实现这一目标? 谢谢。
答案 0 :(得分:0)
您可以使用toArray()覆盖模型中的值
public function toArray()
{
return [
'oponent' => $this->last_sender. " " .$this->last_reciever,
];
}
或使用laravel API资源
class User extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
如果您想使用laravel api资源返回集合
Route::get('/user', function () {
return UserResource::collection(User::all());
});