简体   繁体   中英

laravel returning relationships with eloquent and laravel

In my database I am an organisations table this table has the following relationships,

Many-to-many with users Many-to-many with clients One-to-many with projects

In turn these relationships have other relationships for example projects

One-to-one with client

In my controller I am doing the following,

    $organisation = Organisation::all();

    $organisation->load('users');
    $organisation->load('clients');
    $organisation->load('teams');
    $organisation->load('projects');

    return Response::json($organisation, 200);

So get all the organisations and there relational data.

However what I wanting to do is also get the relationships of relationships, so for example get the client that is related to each project that an organisation has? I thought that doing what I am doing would have worked but obviously not.

Here are my models,

Organisation,

class Organisation extends Eloquent {

//Organsiation __has_many__ users (members)
public function users()
{
    return $this->belongsToMany('User')->withPivot('is_admin');
}

//Organisation __has_many__ clients
public function clients()
{
    return $this->belongsToMany('Client');
}

//Organisation __has_many__ projects
public function projects()
{
    return $this->belongsToMany('Project');
}

}

Projects

class Project extends Eloquent {

protected $fillable = [
    'name',
    'description',
    'total_cost',
    'start_date',
    'finish_date',
    'sales_person',
    'project_manager',
    'client_id',
    'organisation_id',
    'user_id'
];

public function organisations()
{
    return $this->belongsToMany('Organisation');
}

public function salesperson() {
    return $this->belongsTo('User', 'sales_person');
}

public function clients() {
    return $this->belongsTo('Client', 'client_id');
}   

}

Clients

class Client extends Eloquent {

    public function organisations()
    {
        return $this->belongsToMany('Organisation');
    }

    public function users()
    {
        return $this->belongsToMany('User');
    }

    public function projects()
    {
        return $this->hasMany('Project');
    }
}

Have you tried:

$organisations = Organisation::with('projects', 'projects.clients')->all();

foreach($organisations as $organisation) {

    foreach($organisation->projects as $project) {

        foreach($project->clients as $client) {

            echo $client->name;

        }             

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM