2016-10-28 11 views
0

私はチケットテーブルを持っています。メインチケットテーブルhasOneお客様は、 customerテーブルはuserテーブルに属します。LaravelでhasOne関係で3番目のテーブルをクエリする方法は?

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

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

index.blade.phpメインテーブルはチケットです。それはユーザーと顧客にforeign_keyを持っています。 Customersテーブルには、first_nameとlast_nameを含む外部キーがあります。

問題:私は$アイテム - > customer-> FIRST_NAMEにアクセスしたいです。

エラー:SQLSTATE [42S22]:見つからないカラム:1054不明な列 'users.ticket_id' 内の '節'(SQL:選択* usersdeleted_atがnullでusersusersからticket_id = 1と usersticket_idは、任意の助けを理解され

ヌルリミット1)ではありません。

答えて

1

あなたのスキーマとの関係は以下のように、あなたはあなたのコードを書くことができ、適切に定義されている場合:あなたが示すエラーがusersテーブルdosn」ことを示唆している

@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. tはticket_idを含みます。あなたはそれをチェックしましたか(多分あなたはマイグレーションを実行することを忘れていましたか?)

  2. あなたの主probkemそのためTicketクラスに関係する方法を変更することによって解決されるべきである:


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

第2引数は、関連するテーブルからの外部キーであるべきである(hasManyと同じ関係)。

+0

私を助けてくれてありがとう。 –

関連する問題