I've currently no idea how to get this done in a smart way. I would like to prevent writing tons of querys. First my table design:
users:
|id|username|
tickets:
|id|user_id|
ticket_replies:
id|ticket_id|user_id|
files:
|id|ticket_replie_id|name
my controllers:
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');
}
The relation is like following, a user has many tickets. Each ticket has many ticket_replies. A ticket_replie hasOne attachment (file). Now I need to retrieve the name of a file for a given ticket & ticket_replie_id. In my controller I use this at the moment:
$ticket = Auth::user()->tickets()->where('tickets.id', $id)->where('files.ticket_replie_id', $attachment_id)->firstOrFail();
Laravel generates me this query & error:
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
The query must be something like:
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
When I run this query in my database, it returns the needed informations. Is my way to retrieve the information okay? Where's my fault, because at the moment the query generated by Eloquent isn't working as described above. In case there's a easier way, just tell me. It seems like eloquent isn't able to get a relation between ticket and file. How to tell eloquent there's a relation using ticket_replie?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire