Siper
Siper

Reputation: 1195

Laravel - Get info about user via ID from relationship

I've a three tables: for tickets, replies from ticket and with users. I want get ticket with replies from it and data about respondent. My tables looks something like this:

User:

ID | Username | Email | ...

Tickets:

ID | title | user_id | active | ...

Tickets_Replies:

ID | tickets_id | message | user_id | ...

How it should look in Eloquent ORM? At this moment I've

User:

<?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');
    }
}
?>

And Tickets:

<?php

class Tickets extends Eloquent {    
    public function replies() {
        return $this->hasManyThrough("Tickets_Replies", "User");
    }
}
?>

I've bug somewhere because search "tickets_id" column un Users Table. How can I fix this?

In SQL Query it should looks:

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]

Upvotes: 0

Views: 1079

Answers (1)

jah
jah

Reputation: 1305

You should change your table names to users, tickets and ticketreplies. That's the best practices for laravel and the way i've setup your relationships below:

User:

<?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');
        }

    }
?>

Ticket:

<?php

    class Ticket extends Eloquent {  

        public function replies() {
            return $this->hasMany('TicketReply');
        }

        public function user()
        {
            return $this->belongsTo('User');
        }

    }

?>

How to get your data:

<?php
    Ticket::with('replies', 'replies.user')->find('id of ticket here');
?>

That will get you a Ticket model with the nested relationships you asked for. (:

Upvotes: 2

Related Questions