【发布时间】:2016-02-09 20:35:13
【问题描述】:
我目前不知道如何以聪明的方式完成这项工作。我想防止编写大量查询。 首先是我的餐桌设计:
users:
|id|username|
tickets:
|id|user_id|
ticket_replies:
id|ticket_id|user_id|
files:
|id|ticket_replie_id|name
我的控制器:
user:
public function tickets()
{
return $this->hasMany('App\ticket');
}
ticket:
public function ticket_replie()
{
return $this->hasMany('App\ticket_replie', 'ticket_id', 'id');
}
ticket_replie:
public function file()
{
return $this->hasOne('App\File', 'ticket_replie_id', 'id');
}
每个ticket_replie 只能与一个附件相关(每个ticket_replie 只能一个附件),这就是我使用hasOne 关系的原因。 现在我需要检索给定票证和票证_replie_id 的文件名。 在我的控制器中,我现在使用它:
$ticket = Auth::user()->tickets()->where('tickets.id', $id)->where('files.ticket_replie_id', $attachment_id)->firstOrFail();
Laravel 生成我这个查询和错误:
select * from `tickets` where `tickets`.`user_id` = 1 and `tickets`.`user_id` is not null and `tickets`.`id` = 43 and `files`.`ticket_replie_id` = 39 limit 1
Column not found: 1054 Unknown column 'files.ticket_replie_id' in 'where clause
查询必须是这样的:
select * from `tickets`, `files` where `tickets`.`user_id` = 1 and `tickets`.`user_id` is not null and `tickets`.`id` = 43 and `files`.`ticket_replie_id` = 39 limit 1
当我在我的数据库中运行此查询时,它会返回所需的信息。我检索信息的方式可以吗?我的错在哪里,因为目前 Eloquent 生成的查询无法按上述方式工作。如果有更简单的方法,请告诉我。
我知道 eagerload,我试过这个:
$ticket = Auth::user()->tickets()->with(['file'=>function($f) use ($attachment_id) { $f->where('files.ticket_replie_id', $attachment_id); } ])->where('tickets.id', $id)->where('files.ticket_replie_id', $attachment_id)->firstOrFail();`.
结果:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'files.ticket_replie_id' in 'where clause' (SQL: select * from `tickets` where `tickets`.`user_id` = 1 and `tickets`.`user_id` is not null and `tickets`.`id` = 43 and `files`.`ticket_replie_id` = 39 limit 1)
故障是因为票证和文件模型之间没有直接的“关系”还是我错了?
【问题讨论】:
标签: php mysql eloquent laravel-5.1 relationship