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

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

首先是一对多:

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

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

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

PHP

/**

* 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');

}

}

PHP

/**

* 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];

}

}

原文链接:https://www.f2er.com/thinkphp/60450.html

猜你在找的ThinkPHP相关文章