Retrieving a single colum from a pivot table - Laravel 5 - php

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.

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

A user should have one genre.
Therefore, your models should contain the following relations:
User.php
public function genre() {
return $this->hasOne('App\Genre');
}
Genre.php
public function artists() {
return $this->belongsToMany('App\User');
}

Related

Model connections is not working properly - Laravel

I'm trying to display a tag that is selected by the user. The tag name is in the tags table. The tagpost table has the mapping between the tag and the user.
The following is the User model, where the primary key in users table is id, and var_id can be many types and 2 is for users (not sure if the below where condition is correct):
public function tagpost()
{
return $this->hasMany('App\tagpost', 'var_id')->where('type',2);
}
The following is the tagpost model:
public function tags()
{
return $this->belongsToMany('App\tag','id');
}
public function users()
{
return $this->belongsToMany('App\User');
}
The following is the tag model :
public function tagposts()
{
return $this->hasMany('App\tagpost', 'var_id');
}
The following query is not working in the blade :
<option>{{ Auth::user()->tagpost()->tags()->select('t_name')->first()->t_name}} </option>
Error in blade :
Call to undefined method Illuminate\Database\Query\Builder::tags()
You are calling the relations as method whereas they should be called as property like this. Also i suggest you the laravel documentation
<option>{{ Auth::user()->tagpost->tags->select('t_name')->first()->t_name}} </option>
If tagpost is just the relation table why don’t you define a method tags() on the User model, using the tagposts table as the pivot so you can just do Auth::user()->tags()?
Your code won’t work because ->tagpost() returns the Relation itself and not the tagpost models...

Multiple relationship between tables in Laravel 5.4

I have 3 tables (items, category_questions_mapping and category_questions) in mysql database in which I have the following columns:
items table has following columns:
item_id, uuid, radius, category_id
category_questions_mapping has following columns:
category_id, category_question_id
category_questions has following columns:
category_question_id, data
I have created the model for the items table which is Items.php in which I have created the following method:
public function category_questions() {
return $this->hasOne('App\CategoryQuestionsMapping','category_id','category_id');
}
The above method is basically a relationship between category_id of the items table with the category_id of category_question_mappings table
Problem Statement:
I am wondering what changes I should make in the above method so that I am able to pull data column value from category_questions table. Is there any we can make a relationship in the above method so that it can pull the data column ?
The above method will be used in the controller for display.
To acess the category_question table columns you must define the relationship on the category_question_mapping model too, like:
public function category_questions() {
return $this->hasOne('App\CategoryQuestions','category_question_id','category_question_id');
}
then acess the field you want like $items->category_questions_mapping->category_questions->data.
By the way, I'd recommend naming the first relationship you showed like category_questions_mapping() as it is linking with the category_questions_mapping table.
You can't change only the category_questions method to solve the problem. But you can make 2 relations in 2 models and query data through 2 relations.
// App\Item
public function category_questions_mapping() {
return $this->hasOne(CategoryQuestionsMapping::class, 'category_id', 'category_id');
}
// App\CategoryQuestionsMapping
public function category_question() {
return $this->hasOne(CategoryQuestion::class, 'category_question_id', 'category_question_id');
}
// Somewhere else
// Get data:
$data = $item->category_questions_mapping->category_question->data;
// Find by data:
$items = \App\Item
::whereHas('category_questions_mapping.category_question', function ($query) {
$query->where('data', 'foo');
})
->get();
Your relationship use like this :
public function category_questions() {
return $this->belongsToMany('App\CategoryQuestions','category_questions_mapping','category_id', 'category_question_id);
}

Laravel Eloquent get a relation that matches a value in pivot table

I need to get model that must match with the value stored in a pivot table, but unfortunately i couldn't get the solution.
Here is my schema
PEROPERTY TABLE
id
FILTER TABLE
id
FILTER_OPTION TABLE
id
filterId
FILTER_OPTION_TRANSLATE TABLE
optionId
languageId
title
PROPERTY_FILTER TABLE
propertyId
filterId
optionId
What i wanto to do is:
#foreach($property->filters as $filter)
{{ $filter->option->translate->title }}
#endforeach
but here the problem for me is how to say get option matches optionId in PROPERTY_FILTER TABLE
My models:
PROPERTY MODEL
public function filters()
{
return $this->belongsToMany(Filter::class, 'PROPERTY_FILTER','propertyId','filterId');
}
FILTER MODEL
public function option()
{
return $this->hasMany(Filter_Option::class, 'filterId');
}
FILTER OPTION MODEL
public function translate()
{
return $this
->hasOne(Filter_Option_Translate::class, 'optionId')
->where('langId', currentLanguage()->langId);
}
I hope i can get some help, thanks from now.
I solved my problem by using pivot table as seperated model.
I was trying to get 3 level far relation through pivot table but even intermediate model couldn't solve my problem, and i just tried a seperated model.
Firstly, i created Property_Filter model that represents property_filter pivot table and I added filter and option methods as below shown:
public function filter()
{
return $this->belongsTo(Filter::class, 'filterId');
}
public function option()
{
return $this->belongsTo(Filter_Option::class, 'filterValue');
}
Then converted filters relationship method
public function filters()
{
return $this->belongsToMany(Filter::class, 'PROPERTY_FILTER','propertyId','filterId');
}
to
public function filters()
{
return $this->hasMany(Property_Filter::class,'propertyId');
}
Now i reach the filter and option selected for iterated filter like below shown:
#foreach($properties as $property)
#foreach($property->filters as $filter) // here i get filters chosen for iterated property
<span class="caption">{{ $filter->filter->translate->entryTitle }}</span> // here i get iterated filters title (translated)
<span class="value">{{ $filter->option->translate->entryTitle }}</span> // here i get chosen option for iterated filter not all options belognsto iterated filter
#endforeach
#endforeach

Get column list with Eloquent relation in laravel

I want to get column list with Eloquent relation in laravel.
When I use this comman
$columns = Schema::getColumnListing('news');
Result is all fields of news table but I want to get relation fields for CategoryNews table.
News model:
public function NewsCategories()
{
return $this->belongsTo('App\CategoryNews');
}
CategoryNews model:
public function News()
{
return $this->hasMany('App\News');
}
You should be able to do something like this:
$columns = Schema::getColumnListing($news->NewsCategories()->getRelated()->getTable()));
Using getRelated() method you are getting related object for relationship (in your case it's App\CategoryNews) and now using method getTable() you can get table name for this model and you can use this table name for getColumnListing() method.

Laravel eager relationships empty query

I have 3 tables : hotels, hotels_data, hotels_types
Table hotels have id, type, stars, etc... type field is set as foreign key referencing type_id in hotels_types. I'm managing to get the correct data from hotels_data but have an empty result on getting hotels_types title and I don't understand why.
The code is the following :
class Hotel extends Eloquent {
public function getList() {
$data = Hotel::select('id','stars')->with('HotelData', 'HotelType')->paginate(10);
return View::make('hotels.index')->with('hotels', $data);
}
public function HotelData()
{
return $this->hasOne('HotelsData')->select('id','hotel_id','title');
}
public function HotelType()
{
return $this->hasOne('HotelType','type_id', 'type')->select('id','type_id','title');
}
}
You're using the wrong relationship for HotelType()
Your Hotel model should use the inverse of hasOne, which is belongsTo, because it contains the foreign key to HotelType (when a table contains a foreign key, it always belongs to the table being pointed to).
The following should work:
public function hotelType() {
return $this->belongsTo('HotelType','type', 'type_id')->select('id','type_id','title');
}
I've obtained the desired result with the following:
Hotel::select('hotels.*','hotels_types.title as type')
->join('hotels_types', 'hotels.type', '=', 'hotels_types.type_id')
->with('HotelData');

Categories