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

报告相同问题?

悬赏问题

  • ¥15 蓝桥oj3931,请问我错在哪里
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染