我有一张门票表。主要门票表 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的
public function customer()
{
return $this->hasOne('App\Models\Customer');
}
/**
* Get the Ticket record associated with the user.
*
*/
public function ticket()
{
return $this->belongsTo('App\Ticket');
}
index.blade.php
@foreach($tickets as $item)
<tr>
<td>{{ $item->customer->first_name }}</td>
</tr>
@endforeach
主表是门票。它为用户和客户提供了 foreign_key 。 Customers表具有包含first_name和last_name的用户的外键。
问题:我想访问 $ item-&gt; customer-&gt; first_name 。
错误:SQLSTATE [42S22]:未找到列:1054未知列&#39; users.ticket_id&#39;在&#39; where子句&#39; (SQL:select * from
users
whereusers
。deleted_at
为空且users
。ticket_id
= 1和users
。ticket_id
不是空限制1)
感谢任何帮助。
答案 0 :(得分: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
答案 1 :(得分:1)
您显示的错误表明users
表格不包含ticket_id
。你检查了一下(也许你忘了运行一些迁移)?
您的主要问题应该通过更改Ticket
类中的关系方法来解决:
public function customer()
{
return $this->hasOne('App\Models\Customer', 'customer_id');
}
第二个参数应该是相关表中的外键(与hasMany
关系相同)。