ThinkPHP5 一对多,多对多关联模型的尝试

前端之家收集整理的这篇文章主要介绍了ThinkPHP5 一对多,多对多关联模型的尝试前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

@H_4030@首先是一对多:

@H403_0@查询卖家自定义分类: 建立卖家表seller,建立分类表category

@H_403_0@

@H_403_0@

@H_403_0@表中记得创建 外键字段  seller_id,categoryid ,

@H
4030@TP5框架中创建两个seller 和categorr模型,

@H
403_0@<?PHP

@H_4030@/**

@H
403_0@ Created by PHPStorm.

@H_403_0@
User: 爱憎分明

@H_4030@* Date: 2018/12/24

@H
4030@* Time: 21:04

@H
4030@*/

@H
4030@namespace appapimodel;

@H
4030@use thinkModel;

@H
4030@class Category extends Model

@H
4030@{

@H
4030@public function seller(){

@H
403_0@return $this->belongsTo('Seller','sellerid');

@H
4030@}

@H
4030@}

@H
403_0@<?PHP

@H_4030@/**

@H
403_0@ Created by PHPStorm.

@H_403_0@
User: 爱憎分明

@H_4030@* Date: 2018/12/23

@H
4030@* Time: 18:55

@H
4030@*/

@H
4030@namespace appapimodel;

@H
4030@use thinkModel;

@H
4030@class Seller extends Model

@H
4030@{

@H
4030@public function category(){

@H
403_0@return $this->hasMany('Category','sellerid');

@H
4030@}

@H
4030@}

@H
403_0@调用模型方法查询关联数据

@H_403_0@//关联读取分类

@H_403_0@public function readcategory(){

@H
4030@$result=0;

@H
4030@$message='';

@H
4030@$categories=[];

@H
403_0@foreach ($this->seller->category as $value){ //这里category为属性 也可以调用category() 方法达到其他目的

@H_403_0@arraypush($categories,$value->getData());

@H
4030@}

@H
4030@if ($categories){

@H
4030@$result=1;

@H
4030@$message='读取成功';

@H
4030@return ['result'=>$result,'message'=>$message,'categories'=>$categories];

@H
4030@}

@H
403_0@}

猜你在找的ThinkPHP相关文章