我有三张桌子:门票,门票和用户回复。我想得到它的回复和有关受访者的数据。我的表看起来像这样:
用户:
ID | Username | Email | ...
门票:
ID | title | user_id | active | ...
Tickets_Replies:
ID | tickets_id | message | user_id | ...
它应该如何看待Eloquent ORM?此刻我已经
了用户:
<?php
class User extends Eloquent {
public function replies() {
return $this->belongsTo("Tickets_Replies");
}
}
?>
Tickets_Replies:
<?php
class Tickets_Replies extends Eloquent {
public function replies()
{
return $this->belongsTo('Tickets');
}
}
?>
和门票:
<?php
class Tickets extends Eloquent {
public function replies() {
return $this->hasManyThrough("Tickets_Replies", "User");
}
}
?>
我在某处犯了错误,因为搜索&#34; tickets_id&#34;列un用户表。我该如何解决这个问题?
在SQL Query中它应该看起来:
select `tickets_replies`.*, `users`.`username`
from `tickets_replies`
left join `users`
on `users`.`id` = `tickets_replies`.`user_id`
where `tickets_replies`.tickets_id = [TICKET_ID]
答案 0 :(得分:2)
您应该将表名更改为用户,故障单和故障单。这是laravel的最佳实践以及我在下面建立你的关系的方式:
用户:强>
<?php
class User extends Eloquent {
public function tickets() {
return $this->hasMany('Ticket');
}
public function replies() {
return $this->hasMany('TicketReply');
}
}
?>
<强> TicketReply:强>
<?php
class TicketReply extends Eloquent {
protected $table = 'ticketreplies';
public function ticket()
{
return $this->belongsTo('Tickets');
}
public function user()
{
return $this->belongsTo('User');
}
}
?>
<强>票:强>
<?php
class Ticket extends Eloquent {
public function replies() {
return $this->hasMany('TicketReply');
}
public function user()
{
return $this->belongsTo('User');
}
}
?>
如何获取数据
<?php
Ticket::with('replies', 'replies.user')->find('id of ticket here');
?>
这将为您提供一个票证模型,其中包含您要求的嵌套关系。 (: