加入belongsToMany并获取所有列

时间:2017-10-17 20:45:32

标签: php mysql laravel-5 eloquent

我有这个方法:

public function menuGroups()
{
    return $this->belongsToMany(Layout::class, '_layout_pivot', 'side_menu_item_id', 'side_menu_group_id')->withTimestamps();
}

结果是这样的(循环之一):

"id" => 1
"label" => "system/menu.settings_group"
"icon" => "icon-settings"
"sort" => 10
"system_employee_id" => 10
"created_at" => "2017-07-19 03:24:06"
"updated_at" => "2017-07-17 00:00:00"

我还有'system_employees'表(只有几个示例列):

+----+----------------+-----------+-----------+-----+---------------------+---------------------+
| id | username       | firstname | lastname  | age | created_at          | updated_at          |
+----+----------------+-----------+-----------+-----+---------------------+---------------------+
|  1 | Raquel46932071 | Raquel    | Heller    |  25 | 2017-04-26 05:03:43 | 2017-07-03 21:13:37 |
|  2 | Brant13975229  | Brant     | Rosenbaum |  30 | 2017-04-25 21:34:46 | 2017-05-07 09:28:27 |
+----+----------------+-----------+-----------+-----+---------------------+---------------------+

来自> belongsToMany的system_employee_id是system_employees的外键,等于system_employees.id

我正在尝试将两者结合起来,以获得system_employee名称。

编辑(根据aynber评论):

我加入这两个并使用paginate(),所以我不能使用get和select,或前缀列:

$this->menuGroups
->leftJoin('system_employees', 'system_employees.id', '=', '_layout_side_menu_groups.system_employee_id')
->paginate($pages, $columns, $pageName, $page);

这就是我得到的:

"id" => 18
        "label" => "Some Insert Tester"
        "icon" => "insico"
        "sort" => 39
        "system_employee_id" => 18
        "created_at" => "2017-07-03 00:28:05"
        "updated_at" => "2017-07-03 00:28:05"
        "type" => 4
        "system_id" => 0
        "username" => "System2017"
        "firstname" => "Rita"
        "lastname" => "Veygand"
        "age" => 0
        "gender" => ""
        "email" => "system@gmail.com"
        "mobile" => ""
        "rank_id" => 1
        "rank_title" => ""
        "status" => 1
        "avatar" => "mysite.com/img/14161939651400nds6k.jpg"
        "password" => "$2y$10$FIL4LmjLVEZ6SgUsRILqPutTEcaGWcmKyIHwPOBbQfHDYdJM5//2."
        "remember_token" => "vUI812NTJZ8RWrlX3g3quBy4quVrue1dnOVZEPzifRJdy85cJPQY7RclYNHU"

问题

如何在不使用查询生成器的情况下从两个表中获取'created_at','updated_at'? 这同样适用于两个表中具有相同名称的任何其他列。

换句话说:有没有办法在belongsToMany中为列添加前缀?

1 个答案:

答案 0 :(得分:0)

由于我使用paginate()而不是get(),我以为我无法指定列。

但是可以做到。

Paginate允许定义列 - 就在那里看着我。

这是适合我的解决方案:

$columns = [
            '_layout_side_menu_groups.created_at AS layout_created_at',
            '_layout_side_menu_groups.updated_at AS layout_updated_at',
            'system_employees.created_at AS system_created_at',
            'system_employees.updated_at AS system_updated_at',
];
$this->menuGroups
->leftJoin('system_employees', 'system_employees.id', '=', '_layout_side_menu_groups.system_employee_id')
->orderBy('_layout_side_menu_groups.' . $columnSorted, $sortOrder)
->paginate($pages, $columns, $pageName, $page);

可以通过这种方式定义所有表中的所有列。