jeudi 20 août 2015

Laravel 5.1 relationship of relationship

Let's say I have three models:

  • Worker
  • Department
  • Company

A Company has many Departments and a Department has many Workers. Now how can I get all the Workers from the company?

I can get all the departments with

Company::find(1)->departments()

I can get all the Workers with

Department::find(1)->workers()

I tried creating a method to the model Company like that:

public function workers()
{
    return $this->departments->map(function($item, $key){
        return $item->workers;
    });
}

The issue rose, when I wanted to call a the method 'where()' on the collection with three arguments and it gave me an empty collection.

Company::find(1)->workers()->where('salary', '>=', '100');

And that returns an empty collection whatever I do. I tried whereLoose, passed '100' as an integer. The following works fine:

Company::find(1)->workers()->where('salary', '100');

Gives me all the workers, who have a salary of 100.

Is there a way to kind of use the Relationships so I can get the Relationship from Company->hasMany('Worker')?

laravel php laravel 5 laravel 4 laravel with laravel tutorial

Aucun commentaire:

Enregistrer un commentaire