简体   繁体   中英

Retrieving a single colum from a pivot table - Laravel 5

I am using a pivot table genre_user to relate user to genre . table contains the following fields

id 
user_id 
genre_id

Following are the model definitions

User.php

public function genres() {
        return $this->belongsToMany('App\Genre');
    }

Genre.php

public function artists() {
        return $this->belongsToMany('App\User');
    }

I am getting the results as a collection when I use the following code

$user = auth()->user();
dd($user->genres);

I want to show the selected genres in a dropdown field of genres. Is it possible to get only the current users genre_id as an array from the pivot table without using a foreach loop.

I think what will help you achieve this behavior is the lists() method. Try something like

$user_genres = auth()->user()->genres()->lists('name','id');

If you are using Forms & HTML package you can just do

{!! Form::select('genres',$user_genres,null) !!}

And here is your dropdown

More info here (scroll down to "Retrieving A List Of Column Values")

A user should have one genre .

Therefore, your models should contain the following relations:

User.php

public function genre() {
    return $this->hasOne('App\Genre');
}

Genre.php

public function artists() {
    return $this->belongsToMany('App\User');
}

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