簡體   English   中英

Laravel 4.2雄辯的關系

[英]Laravel 4.2 eloquent relations

我是laravel的新手,並且一直在舊服務器中使用laravel 4.2。 我必須聯接三個表以獲取所需的數據。 結構如下:

隊列表:

| id | Patient_id | shift_id | 日期|

患者表:

| id | 名稱| 年齡| 性別|

班次表:

| id | 時間|

我需要控制器返回具有患者姓名,班次時間和日期的對象數據。 每個表都有三個模型。 我如何獲得這個? 我一直在嘗試一對多的關系,但無法完成此任務。

口才

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;
   }
}

然后

$queue = Queue::find(1);  

$queue->patient_name;
$queue->shift_date;

這種方法使用了急切的加載

$queue = Queue::with('patient','shift')->find(1);  

$queue->patient->name;
$queue->shift->time;

閱讀文件

你可以做

查詢生成器

       $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);

文檔在這里詳細說明

如果您使用口才很好,則需要模型。 對於每個數據庫表,您可以生成如下模型:

php artisan make:model Queue
php artisan make:model Patient
php artisan make:model Shift

之后該模型需要一些關系,像這樣定義關系。

class Queue extends Model
{
    /**
     * So now the Queue has a relationship with patient.
     */
    public function patient()
    {
        return $this->hasMany('App\Patient','patient_id','id');
    }
}

此代碼塊使您可以對數據庫進行一些更改。

這樣您就可以在隊列中獲得多少患者。

$queue= Queue::find(1);
foreach($queue as $item)
{
echo $item->patient;
}

如果您想獲得有關關系和模型的更多信息,請參考這里:

Laravel雄辯的關系

$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();

這是您的模特兒

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM