如何使用laravel eloquent获取具有相同名称的所有列?

时间:2016-09-07 04:18:46

标签: php laravel laravel-4 laravel-5 eloquent

假设我有2个表格,如下所示:

table_a: (with a corresponding model TableA)
id | (20+ other field) | deleted_at | created_at | updated_at

table_b: (with a corresponding model TableB)
id | a_id | ( 30+ other field ) | deleted_at | created_at | updated_at

现在我正在使用laravel并加入这两个表

$result = TableA::join('table_b', 'table_a.id', '=', 'table_b.a_id')
    ->where('table_b.created_at', '>=', date('Y-m-d'))
    ->get();

问题是当列名与table_a相同时,我无法使用table_b的某个字段。 (即iddeleted_atcreated_atupdated_at

我做了一些搜索,从this question on stackoverflow,我可能会这样做:

$result = TableA::join('table_b', 'table_a.id', '=', 'table_b.a_id')
    ->where('table_b.created_at', '>=', date('Y-m-d'))
    ->select('table_b.id as b_id', 'table_b.created_at as b_created_at')
    ->get();

但是,在使用此方法时,我需要将所有列名添加到select语句中,并且在50多个字段上执行此操作很痛苦。它是一个导出功能,因此所有字段都是必需的。有没有一种方法可以进行必要的重命名,而不会列出不需要重命名来检索所有行的所有其他字段?或者有没有一种方法可以在没有重命名的情况下检索所有行?

P.S。我正在使用laravel 4.这是一个旧项目,更新比列出所有字段更痛苦。

1 个答案:

答案 0 :(得分:1)

不幸的是,Eloquent查询不会对连接表中的字段进行别名,因此具有相同名称的列会相互覆盖。

显而易见的解决方案是重命名列并不总是可行的选项。

另一种解决方案是删除联接并使用查询构建器的 whereHas 方法,该方法允许根据相关模型中的数据过滤数据。因为它使用子选择而不是连接,所以不会覆盖任何列。

您需要做的就是在 TableA 模型中定义关系 table_b

class TableA extends Model {
  public function table_b() {
    return $this->hasOne(TableB::class); //or hasMany, depending on your data model
  }
}

并替换:

$result = TableA::join('table_b', 'table_a.id', '=', 'table_b.a_id')
  ->where('table_b.created_at', '>=', date('Y-m-d'))
  ->get();

$result = TableA::whereHas('table_b', function($query) {
  $query->where('created_at', '>=', date('Y-m-d');
});

这将为您提供所有具有与给定条件匹配的相关TableB记录的TableA记录。