thinkphp6入门(14)-- 多关联模型查询

背景:

有3个数据表,一个User表,一个Cloth表,一个Shoe表。

Cloth表和Shoe表分别和User表通过user_id关联。

thinkphp 6中如何通过模型查询所有用户,其中包括每个用户的cloth和shoe。

多关联模型查询:

1. User模型 (app\model\User.php):

namespace app\model;

use think\Model;

class User extends Model
{
    // 设置表名(如果与默认的表名不同)
    protected $table = 'user';

    // 关联到Cloth模型
    public function cloths()
{
        return $this->hasMany('App\model\Cloth', 'user_id');
    }

    // 关联到Shoe模型
    public function shoes()
{
        return $this->hasMany('App\model\Shoe', 'user_id');
    }
}

2. Cloth模型 (app\model\Cloth.php):

namespace app\model;

use think\Model;

class Cloth extends Model
{
    // 设置表名(如果与默认的表名不同)
    protected $table = 'cloth';

    // 关联到User模型
    public function user()
{
        return $this->belongsTo('App\model\User', 'user_id');
    }
}

3. Shoe模型 (app\model\Shoe.php):

Cloth模型类似,确保Shoe模型也有与User的关联关系。

4. 查询所有用户及其关联的Cloth和Shoe:

在控制器或其他地方,可以这样查询:


use app\model\User;

// 查询所有用户及其关联的Cloth和Shoe数据
$users = User::with(['cloths', 'shoes'])->select();

// 输出结果(例如,使用dump函数)
dump($users);

这段代码首先使用with()方法指定要加载的关联数据(即clothsshoes),然后使用select()方法执行查询。查询结果将是一个包含所有用户及其关联的ClothShoe数据的数组。每个用户对象都会包含与其关联的ClothShoe数据。

5. 增加查询条件


use app\model\User;

// 查询所有用户及其关联的Cloth和Shoe数据
$users = User::with(['cloths', 
   'shoes'=>  function (Query $query) {
          $query->where('is_delete', 0);
    }])->where('is_member', 1)->select();

// 输出结果(例如,使用dump函数)
dump($users);

关于如何解决不同模型间字段名重复的问题,参考:

https://www.kancloud.cn/manual/thinkphp6_0/1037600

效果类似

图片

by 软件工程小施同学 

相关推荐

  1. thinkphp5层with关联查询错误问题

    2024-01-05 11:52:04       31 阅读
  2. thinkphp6入门16)-- cache用法总结

    2024-01-05 11:52:04       43 阅读
  3. thinkphp:数据库条件查询

    2024-01-05 11:52:04       26 阅读
  4. thinkphp6 模糊查找json下的字段值

    2024-01-05 11:52:04       49 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-05 11:52:04       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-05 11:52:04       106 阅读
  3. 在Django里面运行非项目文件

    2024-01-05 11:52:04       87 阅读
  4. Python语言-面向对象

    2024-01-05 11:52:04       96 阅读

热门阅读

  1. Android 收集崩溃(crash)日志并输出到本地

    2024-01-05 11:52:04       66 阅读
  2. css+html 笔记1

    2024-01-05 11:52:04       61 阅读
  3. 编程笔记 html5&css&js 024 HTML表单元素

    2024-01-05 11:52:04       54 阅读