首页 > 解决方案 > 如何通过 1 Model 和 1 Controller 通过 eloquent 关系功能查询 3 表到 1 表数据收集

问题描述

这是我的默认查询。我想转换 Eloquent 查询

这是 TransferController.php

public function index()
    {
        return Transfer::with(['employee','new_office', 'old_office','designation'])
                        ->orderby('id', 'desc')
                        ->get();
    }

这是我的模型 Transfer.php

class Transfer extends Model
{
    protected $table = 'transfers';
    protected $fillable = [
        'employee_id','order_date','join_date','old_office_id', 'new_office_id',
    ];

    protected $primaryKey = 'id';
    public $timestamps = false;

    public function employee(){
        //return $this->belongsToMany(Employee::class);
        return $this->belongsTo(Employee::class, 'employee_id');
    }
    public function new_office(){
        return $this->belongsTo(Office::class, 'new_office_id');
    }
    public function old_office(){
        return $this->belongsTo(Office::class, 'old_office_id');
    }

    public function designation(){
        return $this->belongsToMany(Designation::class, 'employees','id', 'designation_id', 'employee_id');
        //I want to convert this query by eloquent feature.
        // return DB::table('designations')
        //     ->join('employees', 'designations.id', '=', 'employees.designation_id')
        //     ->join('transfers', 'employees.id', '=', 'transfers.employee_id')
        //     ->select('designations.*')
        //     ->get();
    }
}

我无法理解 belgongToMany 或 hasOneThrough 是完美的查询指定()功能不起作用但其他功能很好

标签: laraveleloquent-relationship

解决方案


推荐阅读