学习内容:
视频教程: https://www.kancloud.cn/tpshop/thinkphp5/229540
完全开发手册:https://www.kancloud.cn/manual/thinkphp5/142359
教程中的代码:https://github.com/phpervip/tp5a
建3个表:
地区表
tp_region,
字段:id,name
配送区域表:tp_shipping_area
字段:shipping_area_id,shipping_area_name,
配送区域和地区关联表,
也叫中间表,
tp_area_region,
字段:shipping_area_id,region_id
model,Region中,
<?php
// application/index/model/Region.php
namespace app\index\model;
use think\Model;
class Region extends Model
{
//地区模型 这里不能写反,一定要写成shipping_area_id,region_id
public function shippingArea(){
// 地区表 BELOGNS_TO_MANY 配送区域
return $this->belongsToMany('ShippingArea','area_region','shipping_area_id','region_id');
}
}
model,ShippingArea中,
<?php
// application/index/model/ShippingArea.php
namespace app\index\model;
use think\Model;
class ShippingArea extends Model
{
// 配送区域划分
// 定义多对多关联
// 配送区域模型 这里写反,好象没关系,所以反写一下
public function region(){
// 配送区域 BELOGN_TO_MANY 地区表
return $this->belongsToMany('Region','area_region','region_id','shipping_area_id');
}
}
<?php
// application/index/controller/index3.php
namespace app\index\controller;
use app\index\model\Region;
use think\Controller;
use app\index\model\ShippingArea;
class index3 extends Controller
{
public function test1(){
// 关联新增
// $region = Region::getByName('北京市');
// 新增配送区域,并自动写入枢纽表
// $region->shippingArea()->save(['shipping_area_name'=>'中国首都']);
// 给一个地区,添加一个现有的配送区域
//$region = Region::getByName('北京市');
//$shippingArea = ShippingArea::getByShippingAreaName('中国首都');
// 添加枢纽表数据
//$region->shippingArea()->attach($shippingArea);
// 关联删除
//$region = Region::getByName('北京市');
//$shippingArea = ShippingArea::get(35);
//$region->shippingArea()->detach($shippingArea,true);
//return '配送区域删除成功';
// 先先查关联,还是用到时再查
$region = Region::get(1,'shippingArea');
// print_r($region->shippingArea);
echo $region->shippingArea[0]->shipping_area_name.'===<br/>';
echo $region->shippingArea[1]->shipping_area_name.'===<br/>';
}
}
———- 招募未来大神 ———————–
如果您有利他之心,乐于帮助他人,乐于分享
如果您遇到php问题,百度且问了其他群之后仍没得到解答
欢迎加入,PHP技术问答群,QQ群:292626152
教学相长!帮助他人,自己也会得到提升!
为了珍惜每个人的宝贵时间,请大家不要闲聊。
愿我们互相帮助,共同成长!
加入时留言暗号,php,ajax,thinkphp,yii…