how to join table in laravel - laravel

I have 2 tables
lets say the 1st one have something like id_teacher_a, id_teacher_b
the 2nd table have the detailed information from table 1 (teacher name, teacher address, etc)
i want to show only the teacher name, so how to join them?
my controller
$data['getid'] = Classroom::select(
'classroom.id',
'teacher.id as tchr_id',
'teacher.name as tchr_name'
)
->join('teacher', 'classroom.teacher_id', '=', 'teacher.id')
->first();
when i want to show table of classroom it would be like
#classroom id #teacher_name_a #teacher_name_b
1 a b

The following should work just fine:
DB::table('classrooms')
->join('teacher as ta', 'ta.id', '=', 'classrooms.id_teacher_a')
->join('teacher as tb', 'tb.id', '=', 'classrooms.id_teacher_b')
->select([
'classrooms.id as classroom_id',
'ta.name as teacher_name_a'
'tb.name as teacher_name_b'
])->get();
Alternatively if you have the following to your Classroom model:
class Teacher extends Model
{
public function teacherA()
{
return $this->belongsTo(Teacher::class, 'id_teacher_a');
}
public function teacherB()
{
return $this->belongsTo(Teacher::class, 'id_teacher_b');
}
}
Then you can also do:
Classroom::query()
->with(['teacherA', 'teacherB'])
->map(function ($classroom) {
return [
'classroom id' => $classroom->id,
'teacher_name_a' => $classroom->teacherA->name,
'teacher_name_b' => $classroom->teacherB->name
];
});

Related

How to retrieve data from two table in Laravel Eloquent

I have two DB tables.
education_institutions
id institution_name country city logo description
1 ABC College UK London null null
user_educations
id user_id institution_id grade year
1 1 1 3.2 2010
Relationships with both models are
UserEducation
public function educationInstitution()
{
return $this->hasMany(EducationInstitution::class,'institution_id');
}
EducationInstitution
public function userEducation()
{
return $this->belongsTo(UserEducation::class,'institution_id');
}
Now how can I retrieve all education institutions of a particular user with the institution details from educations_institution table.
I tried something like
public function getUserEducation()
{
$userEducation = auth()->user()->userEducation()
->orderBy('created_at', 'desc')
->get();
return response()->json([
'userEducation' => $userEducation
]);
}
But it retrieves only education institution id like:
I need user educations with corresponding institution details.
You can use with() function for relationship selection.
public function getUserEducation()
{
$userEducation = UserEducation::with('educationInstitution')->where('user_id',auth()->user()->id)
->orderBy('created_at', 'desc')
->get();
return response()->json([
'userEducation' => $userEducation
]);
}

Get values from relationship Laravel

I have a query where I get values from 3 tables, for first 2 I use leftJoin, and is Ok, but for third one I try to get an array of objects, and I am not sure how.
In relationship table a have multiple rows for each ID from People table. HasMany type.
$q = Person::leftJoin('registers', 'people.register_id', '=', 'registers.id')
->leftJoin('relationships', 'people.id', '=', 'relationships.person_id') //if I comment this it works for first 2 tables
->find($id);
return response()->json($q);
Person
public function relationship()
{
return $this->hasMany(Relationship::class);
}
public function register()
{
return $this->belongsTo(Register::class);
}
Relationship
public function person()
{
return $this->belongsTo(Person::class, 'person_id');
}
Register
public function people(){
return $this->hasOne(Person::class);
}
UPDATE -> this works,but is kind of ugly, I think that should be a better way in Laravel
$q = Person::leftJoin('registers', 'people.register_id', '=', 'registers.id')
->find($id);
$q2 = Person::find($id)->relationship;
return response()->json([
'values' => $q,
'relationship' => $q2,
]);
You can just use with like this:
Person::with(['register', 'relationship'])->find($id);

Laravel: How to get data from 3 tables with relationship

I have 3 Tables:
Customers
id
name
Sales
customer_id
sale_date
Contacts
customer_id
contact_date
There aren't any update operations in the contacts table. Each process opens a new record in the contacts table. So, a user can have more than one records in the contacts table.
Here are my relations in models:
Customer
public function contacts()
{
return $this->hasMany(Contact::class);
}
public function sales()
{
return $this->hasMany(Sale::class);
}
Contact
public function customer()
{
return $this->belongsTo('App\Customer', 'customer_id');
}
Sale
public function customer()
{
return $this->belongsTo('App\Customer');
}
I would like to have the latest record of the contacts table and make it join with the other related tables.
Here is the query which I have tried:
$record = Contact::groupBy('customer_id')
->select(DB::raw('max(id)'));
$result = Customer::query();
$result->where('is_active', 'YES');
$result->with('sales');
$result->whereHas('contacts', function ($q) use($record){
return $q->whereIn('id', $record)->where('result', 'UNCALLED');
});
return $result->get();
In the blade file, I get some result in foreach loops. However, I am unable to get the related data from the sales and contacts table.
#foreach($result as $item)
#foreach($item->sales as $sale) // Has no output and gives error: Invalid argument supplied for foreach()
#foreach($item->contacts as $contact) // Has no output and gives error: Invalid argument supplied for foreach()
Can anyone help me how to display the sale and contact date? Or any idea for how to improve this code quality?
If you want the latest record of the contacts you can declare another relationship on the Customer model, e.g.:
public function latest_contact()
{
return $this->hasOne(Contact::class)->latest('contact_date');
}
BTW you can always declare one or more hasOne additional relationship if you have a hasMany in place the foreign key used is the same.
In this way you can retrieve latest_contact eager loaded with your Customer model:
$customer = Customer::with('latest_contact')->find($id);
Or use this relationship in your queries, something like that:
$customers = Customer::where('is_active', 'YES')
->with('sales')
->with('contacts')
->whereHas('last_contact', function ($q){
return $q->where('result', 'UNCALLED');
})->get();
Or that:
$customers = Customer::where('is_active', 'YES')
->with('sales')
->with('contacts')
->with('last_contact', function ($q){
return $q->where('result', 'UNCALLED');
})->get();
If you want you can declare last_contact with the additional where:
public function latest_contact()
{
return $this->hasOne(Contact::class)
->where('result', 'UNCALLED')
->latest('contact_date');
}
This way all other queries should be easier.
I hope this can help you.
I'm not sure, but can you try to do the following:
return Customer::where('is_active', 'YES')
->with([
'sale',
'contact' => function ($query) use($record) {
return $query->whereIn('id', $record)->where('result', 'UNCALLED');
}
])->get();

How can I get records created_by user with role

Hi I have a table "fiches" with the user_id who created the record.
All my users have a role_id.
How can I get all "fiches" where user_id has the role of 'admin' or something else.
User.php
class User extends Authenticatable{
public function role()
{
return $this->belongsTo(Role::class);
}
// Fiches of User
public function fiches()
{
return $this->hasMany(Fiche::class);
}
}
Fiche.php
class Fiche extends Model{
public function user()
{
return $this->belongsTo('App\User');
}
}
My Query
$fiches = Fiche::whereDay('created_at', '=', date('d'))->where('status', '=', 'A Ecouter')->pluck('id')->count();
Fiches table (id, user_id, name, status, created_at)
Users table (id, role_id, name, created_at)
I want to have the Fiches that was created by role == Admin
You need to use whereHas with nested relationship. Assuming your roles table has column type the code will look like:
$fiches = Fiche::whereHas('user.role', function ($query) {
$query->where('type', 'admin');
})->get();
This query will retrieve all fiches that have users with role that has column 'type' of value 'admin'.
Edit:
For your specific case you provided in the comment the query should look like this:
$fichesAEcouterJours = Fiche::whereDay('created_at', '=', date('d'))
->where(function ($query) {
$query->where('status', '=', 'A Ecouter')
->orWhere('status', '=', 'A Reporter');
})
->whereHas('user.role', function($query){
$query->where('name', 'agent');
})
->count();
Or you can use ->whereIn('status', ['A Ecouter', 'A Reporter']) instead. Note that there is no need to call ->get() before ->count() in this case - it's faster to let Eloquent generate SELECT COUNT query than it is to ->get() collection of all rows and call ->count() of that collection.

How to fetch specific columns from multiple tables in Laravel 5?

I have 3 tables,
Country:
id,
name
Province:
id,
name,
country_id
City:
id,
name,
province_id
I have defined relationships in Model as follows,
Country Model:
public function Provinces()
{
return $this->hasMany('App\Province');
}
Province Model:
public function Country()
{
return $this->belongsTo('App\Country');
}
public function Cities()
{
return $this->hasMany('App\City');
}
City Model:
public function Province()
{
return $this->belongsTo('App\Province');
}
I am using the below query, but it overwrites all the data with Country name.
$city = DB::table('cities')
->join('provinces', 'cities.province_id', '=', 'provinces.id')
->join('countries', 'provinces.country_id', '=', 'countries.id')
->select('cities.name','provinces.name','countries.name')
->get();
I want to fetch a result of only City Name, Province Name, Country Name from these tables in laravel 5. Can you help me with that ?
Try just using as:
->select('cities.name as city_name', 'provinces.name as province_name', 'countries.name as country_name')
Would you try with this :
$city = DB::table('cities')
->join('provinces', 'cities.province_id', '=', 'provinces.id')
->join('countries', 'provinces.country_id', '=', 'countries.id')
->get(['cities.name', 'provinces.name', 'countries.name']);
I hope it helps you !
ok this is going to be a specific answer
learn about realtions in laravel and look at these
class example1 extends Model
{
public function examplefunction() {
return $this->hasMany('App\othermodel', 'id');
}
}
then use this query
$abc=example1::with('examplefunction')->get();
and there you go just take a look at a laravel relationship by using this u can get combined result
$products = User::select('id', 'email', 'first_name', 'last_name','country_code','mobile')->get()->toArray();
$gaurang = Ticket_Thread::select('body','title','resolv_note')

Resources