控制器:
class Theme extends Controller
{
/**
* @url /theme?ids=:id1,id2,id3...
* @return array of theme
* @throws ThemeException
* @note 实体查询分单一和列表查询,可以只设计一个接收列表接口,
* 单一查询也需要传入一个元素的数组
* 对于传递多个数组的id可以选用post传递、
* 多个id+分隔符或者将多个id序列化成json并在query中传递
*/
public function getSimpleList($ids = '')
{
$validate = new IDCollection();
$validate->goCheck();
//第二种方式 (new IDCollection())->goCheck()
$ids = explode(',', $ids);
$result = ThemeModel::with('topicImg,headImg')->select($ids);
if ($result->isEmpty()) {
throw new ThemeException();
}
return $result;
}
模型:
class Theme extends BaseModel
{
protected $hidden = ['delete_time', 'topic_img_id', 'head_img_id'];
/**
* 关联Image
* 要注意belongsTo和hasOne的区别
* 带外键的表一般定义belongsTo,另外一方定义hasOne
*/
public function topicImg()
{
return $this->belongsTo('Image', 'topic_img_id', 'id');
}
public function headImg()
{
return $this->belongsTo('Image', 'head_img_id', 'id');
}
}
BaseModel基类模型:看我个人文章里的swiper的接口代码截图
路由:
// 注意:控制器中接收到的是ids=?是字符串,在postman中测试的时候?ids=1,2,3....
Route::get('api/:version/theme', 'api/:version.Theme/getSimpleList');
postman的截图: