联合查询换成 Eloquent ORM 应该怎么写

Admin用户模型

<?php

namespace App\Models;

class Admin extends User

    public function adminGroup()
    {
      return $this->hasOne(AdminGroup::class,'id', 'group_id');
    }

AdminGroup用户组

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class AdminGroup extends Model
{
    protected $fillable = [
      'group_name','group_desc'
    ];

    public function admin()
    {
        return $this->belongsTo(Admin::class, 'group_id', 'id');
    }
}

控制器中

<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class AdminGroupsController extends Controller
{
    public function index()
    {
        $user = Admin::with('adminGroup')->get();
        echo $user;
    }

前端显示
[{"id":1,"name":"admin","setter":"admin","status":1,"real_name":"wangjing","mobile":null,"job_id":null,"job_tel":null,"seat":1,"count":null,"last_login_ip":"127.0.0.1","last_login_date":null,"created_at":null,"updated_at":"2019-04-15 09:20:03","group_id":1,"admin_group":{"id":1,"group_name":"PHP","group_desc":"PHP","created_at":"2019-04-16 16:11:45","updated_at":"2019-04-16 16:11:49"}}]

但是我期望的显示的是
[{"id":1,"name":"admin","setter":"admin","status":1,"real_name":"wangjing","mobile":null,"job_id":null,"job_tel":null,"seat":1,"count":null,"last_login_ip":"127.0.0.1","last_login_date":null,"created_at":null,"updated_at":"2019-04-15 09:20:03","group_id":1,group_name":"PHP","group_desc":"PHP"}}]

如果用别的方法

SELECT
    admins.*,
    admin_groups.group_name

FROM
    admins
    LEFT JOIN admin_groups ON admins.group_id = admin_groups.id

大佬们进来看下呗

如果我用Eloquent ORM 应该怎么做?

《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
讨论数量: 2

暂时没方法,如果一定要这种格式可以直接jion

1年前 评论
Epona

ORM也支持join方法

1年前 评论

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!