thinkphp 关联模型 一对多关联 主副表查询

一对多关联查询

namespace app\model;

use think\Model;

class Users extends Model
{
    // 模型中定义一对多关系的方法 用于建立当前模型与另一个模型之间的关系, 例如: 当前数据表对应的外键表
    // profile 自定义方法名  Profile::class 关联数据表的模型文件类名
    public function profile()
    {
        // hasMany模式 一对多关系查询 在主表里面 查询 副表的数据
        // 主表关联副表 hasMany('关联模型名', ['关联外键','主键']) [users_id, id]
        // 关联模型名 必须的: 关联模型名或者类名 Profile::class
        // 外键:默认的外键是当前模型名(不含命名空间)+_id, 例如: 当前模型名是Users, 默认的外键是users_id
        // 主键:主键是当前模型的主键, 默认会自动获取也可以指定传入
        return $this->hasMany(Profile::class, 'users_id', 'id');
    }
}

使用的地方 类里
<?php

namespace app\controller;

use app\BaseController;
use app\model\Profile;
use app\model\Users;


class Login extends  BaseController
{
    public function index()
    {
        //  一对多关系查询
        // 查询副表的数据
        // $user = Users::find(1);
        // return $user->profile;
        // $data = $user->profile->where('id', '>', 2);
        // $data = $user->profile()->where('id', '>', 3)->select();

        // 查询主表的数据
        // has() 查询副表大于2条的主表数据 返回对应的主表数据
        // $data =  Users::has('profile', '>', 2)->select();

        // hasWhere() 查询副表的数据 返回对应的主表数据
        // profile 关联的 副表模型名
        // $data = Users::hasWhere('profile', ['id' => 1])->select();
        // 闭包形式
        // $data = Users::hasWhere('profile', function($query) {
        //     return $query->where('id','>',10);
        // })->select();

        // 新增
        // $data = Users::find(1);
        // $data->Profile()->save(['hobby' => 'thinkphp']);

        // 删除  删除的是主表 id为1的 和 id为1副表关联的数据
        $users = Users::with('profile')->find(1);
        $users->together(['profile'])->delete();

        return $users;
    }
  }

posted on 2024-01-23 22:46  完美前端  阅读(297)  评论(0)    收藏  举报

导航