【问题标题】:laravel returning relationships with eloquent and laravellaravel 返回与 eloquent 和 laravel 的关系
【发布时间】:2015-01-29 19:21:52
【问题描述】:

在我的数据库中,我是一个组织表,该表具有以下关系,

与用户的多对多 与客户多对多 与项目一对多

这些关系又具有其他关系,例如项目

与客户一对一

在我的控制器中,我正在执行以下操作,

    $organisation = Organisation::all();

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

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

所以获取所有组织和相关数据。

但是我想做的也是获取关系的关系,例如获取与组织拥有的每个项目相关的客户?我认为做我正在做的事情会奏效,但显然不行。

这是我的模型,

组织,

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

}

项目

类项目扩展 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');
}   

}

客户

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

【问题讨论】:

    标签: php mysql laravel relational-database eloquent


    【解决方案1】:

    你试过了吗:

    $organisations = Organisation::with('projects', 'projects.clients')->all();
    
    foreach($organisations as $organisation) {
    
        foreach($organisation->projects as $project) {
    
            foreach($project->clients as $client) {
    
                echo $client->name;
    
            }             
    
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-22
      • 1970-01-01
      • 2016-11-21
      • 1970-01-01
      • 2020-12-23
      • 2021-11-06
      • 1970-01-01
      • 2014-02-01
      • 2021-07-04
      相关资源
      最近更新 更多