标题说明了一切,但举一个例子。我有一个Member
记录和一个Group
。成员可以拥有许多组的成员资格,而一个组可以拥有许多成员。 (所以这是多对多的,我会有一个数据透视表。)
现在,每个小组都有会员等级。例如,(免费,免费,优质,超级保费)。所以membership_grade
属于数据透视表,对吧?但这是问题,并非所有群体都有相同的分数。有些人可能只有免费和免费增值,有些人可能拥有全部。
在fields.yaml
枢轴模型的Membership
中,我将membership_grades
定义为 Relation Widget ,如下所示:
pivot[grade]:
label: Membership Grade
span: full
type: relation
nameFrom: name
和Membership.php
中的关系一样:
public $belongsTo = [
'grade' => [
'Acme\Models\Grade',
]
];
显然,这会暴露所有成绩,因为我从Grade
模型中提取数据。我想要的是公开该组可用的成绩,而不是所有。
我想做的事情(但我没有,因为它似乎不可能)是试图从集团的grades
关系中提取数据,但我怎么想这样做呢? (由于Relation
小部件管理模型的关系,我不能简单地从其他来源提取数据。)
我也试过scopes
,但我怎么想通过现在的小组?因为它需要作为过滤器,如下所示:
// Membership.php
public $belongsTo = [
'grade' => [
'Acme\Models\Grade',
'scope' => 'filteredIt'
],
// added this relationship to try the scopes approach
'group' => [
'Acme\Models\Group'
]
];
// Grade.php
public function scopeFilteredIt($query, Membership $m)
// yes, the second parameter in the scope will be the
// current Membership model. I've tried it.
{
// this won't work, since we want the overall relation filter;
// an instance of Membership won't help.
// this would work if I can find a way to pass the
// current Group (record) selected, and get its grades, then use it here.
return $query->whereIn('id', $m->group->grades->pluck('id')->all());
}
有什么想法吗?
答案 0 :(得分:1)
我在post values
ajax调用期间注意到了一些pivot model
。
当您add new record
以及您的枢轴模型打开时post values
是这样的
Array (
[_relation_field] => groups
[_relation_extra_config] => W10=
[foreign_id] => 1
[_session_key] => VrSCoKQrSkIsZNGIju5QIqpdbS3AADoGQRHAsv1e
)
好消息是我们现在可以获得foreign_id
,因为它将是您的selected group id
我们可以在创建时使用,for update
时间you know
我们有relation so we use that
。
public function scopefilteredIt($query, Membership $m)
{
// we are checking relation is there or not
if($m->group) {
// yes group is there we use it
return $query->whereIn('id', $m->group->grades->pluck('id')->all());
}
else {
// seems new record then use foreign_id
$foreign_id = post('foreign_id'); //<-this will be your selected group id
if($foreign_id) { // <- double check if its there
$group = Group::find($foreign_id);
return $query->whereIn('id', $group->grades->pluck('id')->all());
}
}
return $query;
}
如果您遇到任何问题,请发表评论。
检查帖子
public function scopefilteredIt($query, Membership $m)
{
// will show flash message with post data array
$post = print_r(post(), true);
\Flash::success($post);
// we are checking relation is there or not
if($m->group) {
// yes group is there we use it
return $query->whereIn('id', $m->group->grades->pluck('id')->all());
}
else {
// seems new record then use foreign_id
$foreign_id = post('foreign_id'); //<-this will be your selected group id
if($foreign_id) { // <- double check if its there
$group = Group::find($foreign_id);
return $query->whereIn('id', $group->grades->pluck('id')->all());
}
}
return $query;
}