简体   繁体   中英

Laravel ManyToMany retrieving data

I'm new to Laravel and breaking my head trying to work with relationships.

I have 2 tables: members groups

And a pivot table: 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:

@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. The only one that works is this one: $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); you should use group.group_id instead of groups.group_id and also use first() method.

$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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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