<?php
namespace App\Services\v1;
use Validator;
use App\Group;
use App\GroupPrivacy;
use Illuminate\Support\Facades\File;
class GroupService {
protected $supportedIncludes = [
'groupCases' => 'group_cases',
'groupUsers' => 'group_users'
];
protected $clauseProperties = [
'visibility'
];
public function getGroups($parameters) {
if (empty($parameters)) {
return $this->filterGroups(Group::all());
}
$withKeys = $this->getWithKeys($parameters);
$whereClauses = $this->getWhereClause($parameters);
return Group::with($withKeys)->where($whereClauses)->get();
}
protected function getWithKeys($parameters) {
$withKeys = [];
if (isset($parameters['include'])) {
$includeParams = explode(',', $parameters['include']);
$includes = array_intersect($this->supportedIncludes, $includeParams);
$withKeys = array_keys($includes);
}
$withKeys[] = 'groupPrivacy';
return $withKeys;
}
protected function getWhereClause($parameters) {
$clause = [];
foreach ($this->clauseProperties as $prop) {
if (in_array($prop, array_keys($parameters))) {
$clause[$prop] = $parameters[$prop];
}
}
return $clause;
}
}
你好,
我想从有条件的表中获取一些数据。
我的要求:/api/v1/groups?include=&visibility=0
我正在尝试获取可见性为 0 的组。但是 group_privacy 表中的可见性列。所以我在他们之间建立了关系:
群组隐私模型:
class GroupPrivacy extends Model {
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'visibility',
'notification'
];
public function groups() {
return $this->belongsTo('App\Group', 'group_id', 'id');
}
}
团体模式:
class Group extends Model {
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'user_id',
'group_category_id',
'name',
'description',
'img_path'
];
public function groupPrivacy() {
return $this->hasOne('App\GroupPrivacy', 'group_id', 'id');
}
public function users() {
return $this->belongsTo('App\User', 'user_id', 'id');
}
}
我还自动在我的$withKeys
数组中添加了 groupPrivacy ......
但它给出了一个错误:
SQLSTATE[42S22]:未找到列:1054 'where 子句'中的未知列'可见性'(SQL:select * from
groups
where (visibility
= 0))
这个错误是真的,但我怎么能说“看看 GROUP_PRIVACY 表,你是白痴!!” ?
附:Laravel 5.3
你可以做类似的事情
$group = Group::whereHas('groupPrivacy', function($q){
$q->where('visibility ', '=', 0);
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句