plu*_*iam 13 php join laravel eloquent
Account和 Roleclass Account extends Eloquent
{
protected $table = 'account';
/* [...] */
public function group() {
return $this->belongsTo('Group');
}
}
Run Code Online (Sandbox Code Playgroud)
class Role extends Eloquent {
protected $table = 'role';
public function accounts() {
return $this->hasMany('Account');
}
}
Run Code Online (Sandbox Code Playgroud)
account和roleaccount
-------
id
name
role_id (nullable)
role
----
id
name
Run Code Online (Sandbox Code Playgroud)
我需要accounts按role.name列排序.但是在join(或leftJoin)之后,第二个表中的值会覆盖这些值.这是一些代码:
$response = Account::with('role')->leftJoin('group', 'group.id', '=', 'account.group_id')->get();
Run Code Online (Sandbox Code Playgroud)
之后,在eloquent集合中的值id和name不正确.
此外,我需要返回为eloquent类型模型,因为我在JSON中返回响应,重要的是稍后在JS(解析JSON之后)我可以做到account.role.name.
更改表中字段的名称(例如:id - > account_id和:id - > role_id)将是一种解决方法,但这不是我的情况 - 需要id为每个表命名主键.
[编辑]是的,所以问题很简单:如何解决这个问题?
小智 30
您可以像在普通SQL查询中一样使用"select":
$response = Account::with('role')
->select('account.*')
->leftJoin('group', 'group.id', '=', 'account.group_id')
->get();
Run Code Online (Sandbox Code Playgroud)
http://laravel.com/docs/queries#selects
补充@beech给出的答案,您可以在 select 子句中使用别名,这样您就可以只获取您需要的特定键,例如
Account::with('role')
->select('account.id AS account_id', 'role.id AS role_id', 'account.name AS account_name', 'role.name AS role_name')
->leftJoin('group', 'group.id', '=', 'account.group_id')
->get();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7988 次 |
| 最近记录: |