thinkphp6中hasMany、hasOne 和 belongsTo说明

要求:在thinkphp6中,有一个订单表order查询记录,关联多个goods图片,一个送货地址, 一个用户头像。hasMany、hasOne 和 belongsTo 从模型设置到控制器调用用代码说明

说明:在 ThinkPHP 6 中,如果 Order 模型中已经定义了 belongsTo 关联关系指向 User 模型,那么在 User 模型中不需要再额外定义 hasMany 关联关系指向 Order 模型。

假设我们有以下模型:

  • Order:订单模型
  • GoodsImage:商品图片模型
  • Address:送货地址模型
  • User:用户模型

1. 设置模型关联关系

Order 模型
复制代码
namespace app\model;

use think\Model;

class Order extends Model
{
    // 订单关联商品图片
    public function goodsImages()
    {
        return $this->hasMany(GoodsImage::class);
    }

    // 订单关联送货地址
    public function address()
    {
        return $this->hasOne(Address::class);
    }

    // 订单关联用户
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
GoodsImage 模型
复制代码
namespace app\model;

use think\Model;

class GoodsImage extends Model
{
    // 商品图片关联订单
    public function order()
    {
        return $this->belongsTo(Order::class);
    }
}
Address 模型
复制代码
namespace app\model;

use think\Model;

class Address extends Model
{
    // 送货地址关联订单
    public function order()
    {
        return $this->belongsTo(Order::class);
    }
}
User 模型
复制代码
namespace app\model;

use think\Model;

class User extends Model
{
    // 用户关联订单
    public function orders()
    {
        return $this->hasMany(Order::class);
    }
}

2. 在控制器中调用关联关系

在控制器中查询订单及关联数据
复制代码
namespace app\controller;

use app\model\Order;

class OrderController
{
    public function show($id)
    {
        // 获取订单及关联数据
        $order = Order::with('goodsImages', 'address', 'user')->find($id);

        // 返回订单及关联数据给视图或其他操作
        return view('order/show', ['order' => $order]);
    }
}

在这个示例中,我们在 OrderController 控制器中的 show 方法中使用了 with 方法来预加载订单关联的商品图片、送货地址和用户数据。然后,我们可以在视图中轻松地访问订单及其关联数据。

相关推荐
长安有故里y8 分钟前
tomcat设置预防host头攻击
java·tomcat·firefox
生产队队长9 分钟前
Tomcat问题:启动脚本startup.bat中文乱码问题解决
java·ajax·tomcat
碧海蓝天202217 分钟前
C++法则21:避免将#include放在命名空间内部。
开发语言·c++
张紫娃21 分钟前
idea 常用快捷键
java·ide·intellij-idea
兮动人25 分钟前
Java应用全链路故障排查实战指南:从系统资源到JVM深度诊断
java·开发语言·jvm
风流 少年32 分钟前
Cursor创建Spring Boot项目
java·spring boot·后端
R-sz35 分钟前
导出word并且插入图片
开发语言·c#·word
CodeWithMe36 分钟前
【读书笔记】《C++ Software Design》第一章《The Art of Software Design》
开发语言·c++
wáng bēn40 分钟前
【java17】使用 Word 模板导出带替换符、动态表格和二维码的文档
java·word·itextpdf
脑袋大大的1 小时前
判断当前是否为钉钉环境
开发语言·前端·javascript·钉钉·企业应用开发