You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 8中基于三张表的关联查询实现求助

使用Laravel关联实现指定查询

首先得给三个模型定义好关联关系:

1. 定义模型关联

  • User模型:一个用户拥有多个种植园,添加一对多关联:
// app/Models/User.php
public function plantations()
{
    return $this->hasMany(Plantation::class);
}
  • Plantation模型:一个种植园属于一个用户,同时拥有多个收获记录:
// app/Models/Plantation.php
public function user()
{
    return $this->belongsTo(User::class);
}

public function recoltes()
{
    return $this->hasMany(Recolte::class);
}
  • Recolte模型:一条收获记录属于一个种植园:
// app/Models/Recolte.php
public function plantation()
{
    return $this->belongsTo(Plantation::class);
}

2. 两种查询实现方式

方式一:Eloquent关联预加载(推荐,符合ORM风格)

通过预加载关联,一次性获取所有收获记录及其关联的种植园、用户信息:

$recoltesWithRelations = Recolte::with('plantation.user')->get();

// 遍历结果示例
foreach ($recoltesWithRelations as $recolte) {
    // 访问收获的种植园信息
    $plantationName = $recolte->plantation->name;
    // 访问种植园所属用户信息
    $userName = $recolte->plantation->user->name;
}

方式二:查询构造器JOIN(贴近原生SQL)

如果需要直接拼接三个表的字段返回,用查询构造器的join方法,和你给出的原生SQL逻辑完全一致:

$results = DB::table('recoltes')
    ->join('plantations', 'recoltes.plantation_id', '=', 'plantations.id')
    ->join('users', 'plantations.user_id', '=', 'users.id')
    ->select('recoltes.*', 'plantations.*', 'users.*')
    ->get();

内容的提问来源于stack exchange,提问作者Domeshow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 02:24:22