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

相关推荐
我命由我123454 分钟前
Android Studio - 在 Android Studio 中直观查看 Git 代码的更改
android·java·开发语言·git·java-ee·android studio·android jetpack
hewence14 分钟前
Kotlin协程启动方式详解
android·开发语言·kotlin
苏荷水7 分钟前
万字总结LeetCode100(持续更新...)
java·算法·leetcode·职场和发展
gihigo199819 分钟前
MATLAB运动估计基本算法详解
开发语言·算法·matlab
不光头强31 分钟前
SpringBoot 开发第三天 学习内容
java·spring boot·学习
郝学胜-神的一滴33 分钟前
TCP通讯的艺术:从握手到挥手的优雅对话
开发语言·网络·网络协议·tcp/ip·程序人生
黎雁·泠崖35 分钟前
【魔法森林冒险】12/14 场景系统:5大场景的任务串联
java·开发语言
l1t43 分钟前
在python 3.14 容器中安装和使用chdb包
开发语言·python·clickhouse·chdb
梵刹古音44 分钟前
【C++】函数重写
开发语言·c++