2016-10-28 152 views
0

我有一張門票表。主要門票表hasOne客戶。客戶表屬於用戶表。如何在Laravel中查詢與hasOne關係的第三個表?

Ticket.php

public function user() 
{ 
    return $this->hasOne('App\Models\User'); 
} 

/** 
* Get the TicketStatus record associated with the Ticket. 
* One ticket has only one status 
*/ 
public function ticket_status(){ 
    return $this->hasOne('App\TicketStatus','id','ticket_status_id'); 
} 

/** 
* Get the Customer record associated with the Ticket. 
* One ticket has only one customer 
*/ 
public function customer() 
{ 
    return $this->hasOne('App\Models\Customer', 'id', 'customer_id'); 
} 

Customer.php

public function user() 
{ 
    return $this->belongsTo(User::class); 
} 

/** 
* Get the Ticket that owns the Customer. 
*/ 
public function ticket() 
{ 
    return $this->belongsTo('App\Ticket'); 
} 

user.php的

index.blade.php

@foreach($tickets as $item) 
<tr> 
    <td>{{ $item->customer->first_name }}</td> 
</tr> 
@endforeach 

主要表門票。它有一個foreign_key給用戶和客戶。 Customers表具有包含first_name和last_name的用戶外鍵。我想訪問$ item-> customer-> first_name

錯誤:SQLSTATE [42S22]:柱未發現:在1054未知列 'users.ticket_id' 'where子句'(SQL:。SELECT * FROM users其中 usersdeleted_at爲空和usersticket_id = 1和 usersticket_id不爲空極限1)

任何幫助理解。

回答

1

如果你的模式和關係,正確定義,那麼您可以編寫代碼:

@foreach($tickets as $item) 
<tr> 
    <td>{{ $item->customer->user->first_name }}</td> 
</tr> 
@endforeach 

OR

@foreach($tickets as $item) 
<tr> 
    <td>{{ $item->user->first_name }}</td> 
</tr> 
@endforeach 
+0

謝謝。你是天才! –

+0

工程就像一個魅力。 –

1
  1. 你顯示的錯誤提示users表dosn」 t包含ticket_id。你有沒有檢查它(也許你忘記了運行一些遷移)?

  2. 你的主要probkem應該通過改變關係法Ticket類需要解決的是:


public function customer() 
{ 
    return $this->hasOne('App\Models\Customer', 'customer_id'); 
} 

第二個參數應該是從相關表的外鍵(同樣與hasMany關係)。

+0

感謝您的幫助。 –