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 方法来预加载订单关联的商品图片、送货地址和用户数据。然后,我们可以在视图中轻松地访问订单及其关联数据。

相关推荐
m0_748240251 小时前
Windows编程+使用C++编写EXE加壳程序
开发语言·c++·windows
兮兮能吃能睡2 小时前
R语言模型分析(一)(1)
开发语言·r语言
兔兔爱学习兔兔爱学习2 小时前
Spring Al学习7:ImageModel
java·学习·spring
lang201509283 小时前
Spring远程调用与Web服务全解析
java·前端·spring
wuk9984 小时前
基于有限差分法的二维平面热传导模型MATLAB实现
开发语言·matlab·平面
m0_564264184 小时前
IDEA DEBUG调试时如何获取 MyBatis-Plus 动态拼接的 SQL?
java·数据库·spring boot·sql·mybatis·debug·mybatis-plus
崎岖Qiu4 小时前
【设计模式笔记06】:单一职责原则
java·笔记·设计模式·单一职责原则
Hello.Reader4 小时前
Flink ExecutionConfig 实战并行度、序列化、对象重用与全局参数
java·大数据·flink
熊小猿5 小时前
在 Spring Boot 项目中使用分页插件的两种常见方式
java·spring boot·后端
paopaokaka_luck5 小时前
基于SpringBoot+Vue的助农扶贫平台(AI问答、WebSocket实时聊天、快递物流API、协同过滤算法、Echarts图形化分析、分享链接到微博)
java·vue.js·spring boot·后端·websocket·spring