简体   繁体   English

从数据透视表中检索单个列-Laravel 5

[英]Retrieving a single colum from a pivot table - Laravel 5

I am using a pivot table genre_user to relate user to genre . 我正在使用数据透视表genre_user用户genre关联。 table contains the following fields 该表包含以下字段

id 
user_id 
genre_id

Following are the model definitions 以下是模型定义

User.php User.php

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

Genre.php 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. 是否可以从数据透视表中仅将当前用户genre_id作为数组获取而无需使用foreach循环。

I think what will help you achieve this behavior is the lists() method. 我认为可以通过lists()方法来帮助您实现此行为。 Try something like 尝试类似

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

If you are using Forms & HTML package you can just do 如果您使用的是Forms&HTML包,则可以

{!! 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 . user应具有一种genre

Therefore, your models should contain the following relations: 因此,您的模型应包含以下关系:

User.php User.php

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

Genre.php Genre.php

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM