简体   繁体   English

Laravel ManyToMany检索数据

[英]Laravel ManyToMany retrieving data

I'm new to Laravel and breaking my head trying to work with relationships. 我是Laravel的新手,为与人际关系打交道而挣扎。

I have 2 tables: members groups 我有2张桌子:成员组

And a pivot table: member_group 和数据透视表:member_group

A member can belong to many groups, a group can have many members. 一个成员可以属于多个组,一个组可以具有多个成员。

When I edit a member, I create checkboxes for the groups. 编辑成员时,会为组创建复选框。

I need to mark the ones that the member already has as 'checked' 我需要将成员已经拥有的标记为“已检查”

My edit method: 我的编辑方法:

 public function edit($id)
{
    $cities = City::orderBy('city_name')->pluck('city_name', 'city_id');
    $member = Member::findOrFail($id);
    $groups = Group::all();

    return view('members.edit', compact('member', 'cities', 'groups'));
}

In my edit.blade: 在我的edit.blade中:

@foreach($groups as $group)
 <?php $exists = $member->groups()->where('groups.group_id', $member->group_id); ?>
 @if($exists)
 <input type="checkbox" name="groups[]" value="{{ $group->group_id }}" checked> {{ $group->group_name }}
 @else
 <input type="checkbox" name="groups[]" value="{{ $group->group_id }}"> {{ $group->group_name }}
 @endif

.... ....

All the checkboxes are checked, although the member does not belong to all the groups. 尽管该成员不属于所有组,但选中了所有复选框。

Looking at this post: Stackoverflow post I tried almost everything they offer there, only got errors. 看这篇文章: Stackoverflow文章我尝试了他们在那里提供的几乎所有内容,但只有错误。 The only one that works is this one: $exists = $member->groups->contains($group->group_id); 唯一有效的方法是:$ exists = $ member-> groups-> contains($ group-> group_id);

Don't know about wastefulness or not, it's the only one that works. 不知道是否浪费,这是唯一可行的方法。

I think, in your blade $exists = $member->groups()->where('groups.group_id', $member->group_id); 我认为,在您的刀片中$exists = $member->groups()->where('groups.group_id', $member->group_id); you should use group.group_id instead of groups.group_id and also use first() method. 您应该使用group.group_id而不是groups.group_id ,还应该使用first()方法。

$exists = $member->groups()->where('group.group_id', $member->group_id)->first();

Update: 更新:

Can you try this ? 你可以试试这个吗?

$member = Member::findOrFail($id)->with(['groups'=>function($query){
    $query->selectRaw('groups.group_id');
}])->first();

And in blade: 在刀片中:

$exists = $member->groups()->whereIn('groups.group_id', $member->groups)->first();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM