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

相关推荐
qiuiuiu41321 小时前
正点原子RK3568学习日记-GIT
linux·c语言·开发语言·单片机
草莓熊Lotso21 小时前
《C++ STL list 完全指南:从基础操作到特性对比,解锁链表容器高效用法》
开发语言·c++·list
Boop_wu1 天前
[数据结构] Map和Set
java·数据结构·算法
二王一个今1 天前
Python打包成exe(windows)或者app(mac)
开发语言·python·macos
一勺菠萝丶1 天前
Mac 上用 Homebrew 安装 JDK 8(适配 zsh 终端)完整教程
java·python·macos
毕设源码-朱学姐1 天前
【开题答辩全过程】以 办公自动化管理系统为例,包含答辩的问题和答案
java·eclipse
李宥小哥1 天前
C#基础11-常用类
android·java·c#
C嘎嘎嵌入式开发1 天前
(2)100天python从入门到拿捏
开发语言·python
Stanford_11061 天前
如何利用Python进行数据分析与可视化的具体操作指南
开发语言·c++·python·微信小程序·微信公众平台·twitter·微信开放平台
小许学java1 天前
数据结构-ArrayList与顺序表
java·数据结构·顺序表·arraylist·线性表