如何在Laravel中查询具有hasOne关系的第三个表?

时间:2016-10-28 06:02:53

标签: php html mysql angularjs 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的

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 where   usersdeleted_at为空且usersticket_id = 1和   usersticket_id不是空限制1)

感谢任何帮助。

2 个答案:

答案 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)

  1. 您显示的错误表明users表格不包含ticket_id。你检查了一下(也许你忘了运行一些迁移)?

  2. 您的主要问题应该通过更改Ticket类中的关系方法来解决:

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

    第二个参数应该是相关表中的外键(与hasMany关系相同)。