Pregunta

I am new to Laravel and a bit confused about some definitions of ORM. I am currently working on a simple Trouble ticket management system, and here is my question : (table: column, column,...) tickets : id, description, equipment_id equipments: id, name, vendor_id vendor: id, name

This is a very short resume of my tables and its relations, following Laravel's conventions. How can I build these models?

Basically I need to retrieve, for example, how many tickets were opened to a certain vendor (how many times I called the vendor for support).

Thank you in advance

¿Fue útil?

Solución

What zwacky said is entirely (edit: maybe not entirely correct in the end) true for close relations, but in your situation there is nested relation:

Vendor -> Equipment -> Ticket

Then to retrieve tickets for particular vendor you would define relation on Vendor model like this:

class Vendor extends Eloquent {
  public function equipment()
  {
    return $this->hasMany('Equipment');
  }
  public function tickets()
  {
    return $this->hasManyThrough('Ticket', 'Equipment');
  }


class Equipment extends Eloquent {
  public function tickets()
  {
    return $this->hasMany('Ticket');
  }
  public function vendor()
  {
    return $this->belongsTo('Vendor');
  } 


class Ticket extends Eloquent {
  public function equipment()
  {
    return $this->belongsTo('Equipment');
  }

and to get count of total tickets for the vendor (not currently open):

Vendor::find($id)   // retrieve particular vendor
  ->tickets()->count(); // get count on tickets table

// and this way you retrieve collection of related tickets
Vendor::find($id)   // retrieve particular vendor
  ->tickets; // get Eloquent Collection

Also you may find it helpful: http://softonsofa.com/querying-relations-with-eloquent-in-laravel-4/

Otros consejos

you'd need to declare these relationships within their models. e.g. your Ticket.php model could look like this:

class Ticket extends Eloquent {

    public function equipment()
    {
        return $this->hasOne('Equipment');
    }

    public function vendor()
    {
        return $this->hasOne('Vendor');
    }

    ...
}

for retrieval you'd do it like this:

foreach (Ticket::all() as $ticket) {
    $ticket->vendor()->id;
}

check this section of the laravel docs.

edit: for the specific query how many tickets are open to a certain vendor:

Ticket::where('open', '=', 1)->vendor()->where('id', '=', 42);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top