[英]laravel5.1 retrieve not directly related nested attributes using eloquent
我目前不知道如何以聰明的方式完成這項工作。 我想防止寫出大量的查詢。 首先我的桌子設計:
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只能與一個附件(只有一個attachper ticket_replie)相關,這就是我使用hasOne關系的原因。 現在我需要檢索給定票證和ticket_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)
導致故障的原因是故障單和文件模型之間沒有“關系”,或者我錯了?
你必須加載你的關系,然后你可以應用where條件。 看,這是一個例子。
$courses = Courses::with(['quizzes','chapters'=>function($q){
$q->where('status','1')->orderBy('orderby','ASC');
},'chapters.quizzes','chapters.lessons'=>function($q) use ($lessonid){
$q->where('status','1')->orderBy('orderby','ASC');
},'chapters.lessons.quizzes'])->where('status','1')->where('id',$courseid)->first();
with([])
用於加載模型關系,例如: quizzes
與測驗表的關系, chapters=>function($q)....
它也是一個關系,但我在章節關系等上應用條件
我希望這對你有意義
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.