Flo*_*ach 16 php sql laravel-5.1
我正在尝试从数据库中获取以下内容:
使用以下查询:
static public function getConversation($id)
{
$conversation = DB::table('conversation_messages')
->where('belongsTo', $id)
->join('users', 'conversation_messages.sender', '=', 'users.id')
->join('user_avatars', 'conversation_messages.sender', '=', 'user_avatars.id')
->select('users.name', 'conversation_messages.*', 'user_avatars.name', 'user_avatars.filetype')
->get();
return $conversation;
}
Run Code Online (Sandbox Code Playgroud)
它到目前为止工作正常,但是头像的列名称name与' users'表中的列名称相似.因此,如果我使用此查询来获取输出$conversation->name,则avatar.name覆盖users.name
有没有办法重命名查询输出,如laravel 5.1中的mysql"as"功能?
例如:
$conversation->avatarName
$conversation->userName
Run Code Online (Sandbox Code Playgroud)
Flo*_*ach 38
嗯好吧..我在这里找到了一个简单的解决方案
->select('users.name as userName', 'conversation_messages.*', 'user_avatars.name as avatarName', 'user_avatars.filetype')
Run Code Online (Sandbox Code Playgroud)
如你所知,我已经在table.columnName旁边添加了请求的"as-Feature"
我有以下问题,简化示例:
$result = Donation::join('user', 'user.id', '=', 'donation.user_id')->where('user.email', 'hello@papabello.com')->first();
Run Code Online (Sandbox Code Playgroud)
$result是Donation模型的集合。但要小心:
两个表都有一个“created_at”列。现在created_at执行时显示哪个$result->created_at?我不知道。似乎 eloquent 在进行select *连接时做了隐含的操作,返回模型Donation但具有附加属性。created_at似乎是随机的。所以我真正想要的是Donation用电子邮件返回用户的所有模型hello@papabello.com
解决方案是这样的:
$result = Donation::select('donation.*')->join('user', 'user.id', '=', 'donation.user_id')->where('user.email', 'hello@papabello.com')->first();
Run Code Online (Sandbox Code Playgroud)
小智 7
看一下这个示例,尝试将三个表的职员,客户和预订(数据透视表)合并在一起。
$bookings = \DB::table('bookings')
->join('staffs', 'staffs.id' , '=', 'bookings.staff_id')
->join('customers', 'customers.id' , '=', 'bookings.customer_id')
->select('bookings.id', 'bookings.start_time', 'bookings.end_time', 'bookings.service', 'staffs.name as Staff-Name', 'customers.name as Customer-Name')
->orderBy('customers.name', 'desc')
->get();
return view('booking.index')
->with('bookings', $bookings);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27173 次 |
| 最近记录: |