ThinkPHP5 一对多,多对多关联模型的尝试
首先是一对多:
查询卖家自定义分类: 建立卖家表seller ,建立分类表category
表中记得创建 外键字段 seller_id,category_id ,
TP5框架中创建两个seller 和categorr模型,
<?php
/**
* Created by PhpStorm.
* User: 爱憎分明
* Date: 2018/12/24
* Time: 21:04
*/
namespace app\api\model;
use think\Model;
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 app\api\model;
use think\Model;
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];
}
}