<?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 /組包括= &知名度= 0
我想獲得具有可視性組爲0,但在group_privacy表知名度列。所以我做了他們之間的關係:
GroupPrivacy型號:
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');
}
}
此外,我加入groupPrivacy我$withKeys
自動陣列...但它給出錯誤:
SQLSTATE [42S22]:列未找到:1054未知列 '知名度' 在 'where子句'(SQL:SELECT * FROM
groups
其中(visibility
= 0))
此錯誤事實,但怎麼說呢「看看GROUP_PRIVACY TABLE,你哈哈IDIOT !!」 ?
ps。 Laravel 5.3
這似乎是兩個表之間的關係是不存在的。哪條線是錯誤的原因? – Jiro90
'whereHas'來查詢關係。 – Chay22
如果我寫user_id而不是可見性,它的工作原理。由於group_privacies中的組表中的user_id。 ()子句有效,但where()子句不起作用,如果with()的表中的where參數... – Nevermore