简体   繁体   中英

Laravel 4.2 eloquent relations

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.

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

You can do

Query Builder

       $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

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

$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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