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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?