Reputation: 305
I am new at laravel and have been using laravel 4.2 in an old server. I have to join three tables to get my required data. The structure is as follows:
Queue Table:
| id | patient_id | shift_id | date|
Patient Table:
| id | name | age | gender |
Shift Table:
| id | time |
I need my controller to return object data with patient name, shift time and date. I have three models of each table. How can I obtain this? I have been trying one to meny relations but not been able to complete this task.
Upvotes: 0
Views: 647
Reputation: 382
If you are using eloquent you need to have models. For every database table you can generate models like :
php artisan make:model Queue
php artisan make:model Patient
php artisan make:model Shift
After that model needs some relationships.Define the relationships like this.
class Queue extends Model
{
/**
* So now the Queue has a relationship with patient.
*/
public function patient()
{
return $this->hasMany('App\Patient','patient_id','id');
}
}
This code block allows you to do some changes in database.
So you can get how many patients in the queue like this.
$queue= Queue::find(1);
foreach($queue as $item)
{
echo $item->patient;
}
If you want to get more information about relationships and models refer here :
Laravel Eloquent Relationships
Upvotes: 0
Reputation: 4040
$result = Queue::join('patient', 'queue.parent_id', '=', 'patient.id')
->join('shift', 'queue.shift_id', '=', 'shift.id')
->select('patient.name', 'shift.time', 'queue.date')
->get();
echo "<pre>"; print_r($result); die();
here Queue is your model
Upvotes: 0
Reputation: 7489
Eloquent way
class Queue extends Model
{
protected $appends = ['patient_name','shift_date'];
public function patient()
{
return $this->blongsTo(Patient::class,'patient_id'.'id');
}
public function shift()
{
return $this->blongsTo(Shift::class,'shift_id','id');
}
public function getPatiantNameAttribute()
{
return $this->patient->name;
}
public function getShiftDateAttribute()
{
return $this->shift->time;
}
}
Then
$queue = Queue::find(1);
$queue->patient_name;
$queue->shift_date;
This approach uses eager loading
$queue = Queue::with('patient','shift')->find(1);
$queue->patient->name;
$queue->shift->time;
read docs
Upvotes: 3
Reputation: 2588
You can do
$data = DB::table('queue')
->join('patient', 'queue.parent_id', '=', 'patient.id')
->join('shift', 'queue.shift_id', '=', 'shift.id')
->select('patient.name', 'shift.time', 'queue.date')
->get();
dd($data);
The documentation explains it more here
Upvotes: 1