Tp5关联查询

本文介绍了在ThinkPHP5框架下如何进行模型关联查询,包括Banner和BannerItem的关联操作,以及在Controller中调用这些查询的方法,帮助理解如何获取和处理查询结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

model 

  Banner

 BannerItem

<?php

namespace app\api\model;
use think\Db;
use think\Exception;
use think\Model;
//Banner代码

class Banner extends Model
{
    public function items(){
        return $this->hasMany('BannerItem','banner_id','id');
    }
    
}
<?php

namespace app\api\model;

use think\Model;
//BannerItem 代码

class BannerItem extends Model
{
    //
}

在controller中进行调用

<?php

namespace app\api\controller\v1;
use app\api\model\Banner as BannerModel;
use app\api\validate\IDMustBePositiveInt;
use app\lib\exception\BannerMissException;
use think\Exception;
class Banner
{
    /**
     * 获取指定id的banner信息
     * @url/banner/:id
     * @http GET
     * @id banner的id号
     *
     */
    public function getBanner($id){
        $validate = new IDMustBePositiveInt();
        $validate->goCheck();
        //进行调用
        $banner = BannerModel::with('items')->find($id);
        if(!$banner){
          throw new BannerMissException();
        }
        return $banner;
        //不用json()序列化,tp5直接会序列化,但是是别的不是json而是text/html

    }
}

查询结果

{
    "id": 1,
    "name": "首页置顶",
    "description": "首页轮播图",
    "delete_time": null,
    "update_time": "1970-01-01 08:00:00",
    "items": [
        {
            "id": 1,
            "img_id": 65,
            "key_word": "6",
            "type": 1,
            "delete_time": null,
            "banner_id": 1,
            "update_time": "1970-01-01 08:00:00"
        },
        {
            "id": 2,
            "img_id": 2,
            "key_word": "25",
            "type": 1,
            "delete_time": null,
            "banner_id": 1,
            "update_time": "1970-01-01 08:00:00"
        },
        {
            "id": 3,
            "img_id": 3,
            "key_word": "11",
            "type": 1,
            "delete_time": null,
            "banner_id": 1,
            "update_time": "1970-01-01 08:00:00"
        },
        {
            "id": 5,
            "img_id": 1,
            "key_word": "10",
            "type": 1,
            "delete_time": null,
            "banner_id": 1,
            "update_time": "1970-01-01 08:00:00"
        }
    ]
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值