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 FileNotFoundError 解决方案
  • ¥15 uniapp实现如下图的图表功能
  • ¥15 u-subsection如何修改相邻两个节点样式
  • ¥30 vs2010开发 WFP(windows filtering platform)
  • ¥15 服务端控制goose报文控制块的发布问题
  • ¥15 学习指导与未来导向啊
  • ¥15 求多普勒频移瞬时表达式
  • ¥15 如果要做一个老年人平板有哪些需求
  • ¥15 k8s生产配置推荐配置及部署方案
  • ¥15 matlab提取运动物体的坐标