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 應該怎麼做?