Laravel eloquent - prevent overriding values when joining tables(Laravel eloquent - 在加入表时防止覆盖值)
问题描述
class Account extends Eloquent
{
protected $table = 'account';
/* [...] */
public function group() {
return $this->belongsTo('Group');
}
}
和
class Role extends Eloquent {
protected $table = 'role';
public function accounts() {
return $this->hasMany('Account');
}
}
和数据库表:account
和 role
account
-------
id
name
role_id (nullable)
role
----
id
name
现在的事情是:
我需要按 role.name
列对 accounts
进行排序.但是在 join(或 leftJoin)值被第二个表中的值覆盖后.这是一些代码:
And now the thing is:
I need to order accounts
by role.name
column. But after join (or leftJoin) values are overriden by those from second table. Here's some code:
$response = Account::with('role')->leftJoin('group', 'group.id', '=', 'account.group_id')->get();
之后 id
和 name
的值在 eloquent 集合中不正确.
After that values for id
and name
are incorrect in eloquent collections.
此外,我需要返回的是 eloquent 类型模型,因为我以 JSON 返回响应,重要的是稍后在 JS 中(解析 JSON 后)我可以只做 account.role.name
.
Also, i need the return to be eloquent type models as i'm returning back the response in JSON, where it is important that later in JS (after parsing JSON) i can do just account.role.name
.
更改表中字段的名称(例如:id -> account_id 和:id -> role_id)将是一种解决方法,但这不是我的情况 - 需要将主键命名为 id
每张桌子.
Changing names of fields in tables (like: id -> account_id, and: id -> role_id) would be an workaround, but that's not my case - need to have primary key named id
for every table.
是的,所以问题很简单:如何解决这个问题?
[edit] Yep, so the question is simply: how to solve that problem?
推荐答案
您可以像在普通 SQL 查询中一样使用选择":
You can use 'select' like you would in a normal SQL query:
$response = Account::with('role')
->select('account.*')
->leftJoin('group', 'group.id', '=', 'account.group_id')
->get();
http://laravel.com/docs/queries#selects
这篇关于Laravel eloquent - 在加入表时防止覆盖值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Laravel eloquent - 在加入表时防止覆盖值
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01