laravel - 如何通过 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 是完美的查询指定()功能不起作用但其他功能很好
解决方案
推荐阅读
- javascript - 在jQuery中,事件完成后我如何做某事
- swift - 在 Swift 4、Xcode 10 中禁用 Print("")
- java - 打开位于项目/库的 jar 文件
- python - 过滤请求仅显示 6 分钟及以下时间
- python - 如何使用会话的权重来初始化新会话的权重?
- html - 使用某种样式时通过CSS隐藏Div时为空
- kibana - “不同类型的映射器 [geo.coordinates],current_type [geo_point],merged_type [ObjectMapper]
- jquery - 仅当满足数据库列条件时,如何在数据表列按钮下拉菜单中显示链接
- java - Fortify 指出了一个问题:“Portability Flaw: File Separator”,但是代码中没有硬编码的分隔符
- javascript - 如何强制工作箱更新缓存中的文件?