thinkphp 关联
原理:https://www.kancloud.cn/laowu199/e_dev/448632
示例数据库
hasOne:有一个,加上主谓语应该是 ,A 有一个 B
hasMany:有很多,A 有很多 B
<?php namespace app\common\model; use think\facade\Log; use think\Model; class CategoryModel extends App { protected $table ='category'; protected $pk = 'id'; public function product(){ return $this->hasMany("app\common\model\ProductModel",'category_id','id')->order('id');
//注意第二个参数为外键,第三个参数为CategoryModel里面对应外键的域
}
调用
$categorys = CategoryModel::with(['product'=>function($query){$query->field('id,name,product_code,price1,price2,category_id');}])->all();
参考
$list = User::field('id,name')->with(['profile'=>function($query){$query->field('email,phone');}])->select([1,2,3]); //如果使用field方法指定查询字段,闭包函数内查询字段必须包含当前关联模型的主键,否则会导致关联查询失败 foreach($list as $user){ // 获取用户关联的profile模型数据 dump($user->profile); }
belongsTo:属于, A 属于 B
数据表
model
<?php namespace app\common\model; use think\Model; class ProductModel extends Model { protected $table = 'product'; protected $pk = 'id'; public function category(){ return $this->belongsTo('app\common\model\CategoryModel','category_id','id'); } public function getProductByCategory($categoryId = 0){ return $this->where('id',$categoryId)->select(); } }
调用
$productModel = new ProductModel(); $product = $productModel::find(5); //注意关联查询只能单条数据查询 $category= $product->category; dump($product);
belongsto输出
hasMany调用
$categoryDao = new CategoryModel(); $category = $categoryDao::get(1); $product = $category->product;