1.修改Product .php模型
~~~
<?php
namespace app\api\model;
class Product extends BaseModel
{
protected $autoWriteTimestamp = 'datetime';
protected $hidden = [
'delete_time', 'main_img_id', 'pivot', 'from', 'category_id',
'create_time', 'update_time'];
public function getMainImgUrlAttr($value, $data)
{
return $this->prefixImgUrl($value, $data);
}
}
~~~
2.修改Theme .php模型
~~~
<?php
namespace app\api\model;
class Theme extends BaseModel
{
protected $hidden = ['delete_time', 'topic_img_id', 'head_img_id'];
public function topicImg()
{
return $this->belongsTo('Image', 'topic_img_id', 'id');
}
public function headImg()
{
return $this->belongsTo('Image', 'head_img_id', 'id');
}
//关联product,多对多关系
public function products()
{
return $this->belongsToMany(
'Product', 'theme_product', 'product_id', 'theme_id');
}
public static function getThemeWithProducts($id)
{
$themes = self::with('products,topicImg,headImg')
->find($id);
return $themes;
}
}
~~~
3.修改Theme .php控制器
~~~
<?php
namespace app\api\controller\v1;
use app\api\validate\IDCollection;
use app\api\model\Theme as ThemeModel;
use app\api\validate\IDMustBePostiveInt;
use app\lib\exception\ThemeException;
use think\Controller;
class Theme extends Controller
{
public function getSimpleList($ids = '')
{
$validate = new IDCollection();
$validate->goCheck();
$ids = explode(',', $ids);
$result = ThemeModel::with('topicImg,headImg')->select($ids);
if (!$result) {
throw new ThemeException();
}
return $result;
}
public function getComplexOne($id)
{
(new IDMustBePostiveInt())->goCheck();
$theme = ThemeModel::getThemeWithProducts($id);
if(!$theme){
throw new ThemeException();
}
return $theme;
//return $theme->hidden(['products.summary'])->toArray();
}
}
~~~
结果
![](https://box.kancloud.cn/fdf3122d8ef5e1af4acfeb1483b62b32_1077x700.png)