dsdt66064367 2015-06-17 07:45
浏览 64
已采纳

从数据透视表中检索单个列 - 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.

  • 写回答

2条回答 默认 最新

  • dongqidi2799 2015-06-17 07:55
    关注

    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")

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?