【问题标题】:Laravel 5 - Eloquent relationshipLaravel 5 - 雄辩的关系
【发布时间】:2016-10-10 03:59:59
【问题描述】:

我有如下三张表:

 ------------------------------
| users  | projects  | clients |
|--------|-----------|-------- |
| id     | id        | id      |
| name   | client_id | name    |
|        | user_id   |         |
|        | name      |         |
 ------------------------------

所以基本上关系是这样的:

用户有很多项目
项目属于客户

我的问题是:
如何使用 eloquent 获取用户的所有客户?

似乎我不能使用 hasManyThrough 方法,因为 clients 表中没有 project_id。

所以我希望实现的是:

foreach($users as $user)
     foreach($user->clients as $client) //HOW TO SET UP THIS RELATION?
         foreach($client->projects($user)->get() as $project)

【问题讨论】:

  • 你必须在 laravel 中建立用户和项目模型之间的关系
  • 我知道我可以直接获取用户项目(User hasMany Project),但我希望通过客户端模型获取它们,这意味着即使客户端也不属于用户,只要客户的项目是属于用户的,那么用户可以通过Client获取项目。
  • 你尝试hasManyThrough关系了吗?
  • @JamalAbdulNasir 现在关系就像User hasMany Projects, Project belongsTo Client,我认为hasManyThrough 只适用于一对多关系,因为Client 表中没有project_id
  • 项目对用户的影响是什么?

标签: laravel laravel-5 model eloquent relationship


【解决方案1】:
    $users = User::with('projects')->get();
    
    // organize cleints' project and add for each user  
    foreach ($users as $user) {
        // order projects by client_id
        $projects = Collect($user->projects->toArray());
        $clients = $projects->groupBy('client_id');

        // keep projects data in 'projects' index 
        $temp = array();
        foreach($clients as $client => $projects){
            $temp[$client] = array('projects' => $projects);
        }

        // add clinets data for each user
        $user['clients'] = $temp;
    }

    // output
    foreach($users as $user)
        foreach($user->clients as $client)
            foreach($client['projects'] as $project)
                echo 'user-'.$project['user_id'].', clinet-'.$project['client_id'].', project-'.$project['name'].'<br>';

上面的代码为我生成了这个输出:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 1970-01-01
    • 2015-12-17
    • 2017-08-22
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多