Get column list with Eloquent relation in laravel - php

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.

Related

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 - I want to add column from user table to a relation table

I am not much familiar with eloquent orm in laravel
I have 3 tables they are
-- leads
|
Lead_appointments
and users table
since lead_appointments belongs to leads references id on leads by lead_id
the leads_appointments has a column called created_by with user's id in it
I am trying to query user's name and email along with the result as another column when query using eloquent
Lead Model
class Leads extends Model
{
public function appointments()
{
return $this->hasMany('App\Models\LeadsAppointments', 'lead_id');
}
}
My eloquent query in controller
return $this->lead->with('appointments')->find($id);
the result is like this
In under appointments i also want user email and name along with created by in it
But I couldn't figure it out
Add a relation to LeadAppointment model like this:
class LeadAppointment extends Model
{
public function users()
{
return $this->belongsTo('App\Models\User', 'created_by');
}
}
and change leads model like this:
class Leads extends Model
{
public function appointments()
{
return $this->hasMany('App\Models\LeadsAppointments', 'lead_id')->with('users');
}
}

Laravel 5.2 hasManyThrough relationship issue

I have 3 tables: orders, codes, events
I want to be able to pull all events that an order has, but there's an intermediary table that acts as a pivot table. I've been trying to use hasManyThrough and belongsToMany (along with withPivot) without any luck.
Examples:
public function events()
{
return $this->belongsToMany('events'); // tried this, fails
return $this->hasManyThrough('events', 'codes'); // tried this, fails
return $this->hasManyThrough('events', 'codes', 'event_id', 'id'); // tried this, fails
}
Any pointers would be great!
That's a belongsToMany setup. First, the first parameter is the name of the related class. Second, since your pivot table doesn't follow the Laravel naming conventions, you need to specify the name of the pivot table in your relationship definition:
public function events()
{
// first parameter is the name of the related class
// second parameter is pivot table name
return $this->belongsToMany(Event::class, 'codes');
}
With this setup, you can do:
// get an order
$order = Order::first();
// has all the events related to an order
$events = $order->events;
There are many ways to do this. I will show a one you can get it done.
In Order.php model
public function codes(){
return $this->has('App\Http\Code');
}
In Code.php model
public function orders(){
return $this->belongsTo('App\Http\Order');
}
public function events(){
return $this->hasMany('App\Http\Event');
}
In Event.php model
public function codes(){
return $this->belongsTo('App\Http\Code');
}
Then in you Controller, call them to get required data.
In your case you can do it like below:
$orders = Order::with(['codes' => function($q){
$q->with('events');
})->get();
May be you can get them with nested manner(not sure about this because i didn't tried before posting):
$orders = Order::with('codes.events')->get();
put return $orders; in your controller to see the query.
Enjoy!

Retrieving a single colum from a pivot table - 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.
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');
}

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