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

搜索热词

首先是一对多:

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

edd28a53698fa1c3d86e92970541ff98.png

62b2fb3ceb51816c7199d9530b80c43d.png

表中记得创建 外键字段  seller_id,category_id ,

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

/**

* Created by PHPStorm.

* User: 爱憎分明

* Date: 2018/12/24

* Time: 21:04

*/

namespace appapimodel;

use thinkModel;

class Category extends Model

{

public function seller(){

return $this->belongsTo('Seller','seller_id');

}

}

/**

* Created by PHPStorm.

* User: 爱憎分明

* Date: 2018/12/23

* Time: 18:55

*/

namespace appapimodel;

use thinkModel;

class Seller extends Model

{

public function category(){

return $this->hasMany('Category','seller_id');

}

}

调用模型方法查询关联数据

//关联读取分类

public function read_category(){

$result=0;

$message='';

$categories=[];

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

array_push($categories,$value->getData());

}

if ($categories){

$result=1;

$message='读取成功';

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

}

}

总结

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。