一对多关系查询

问题描述 投票:1回答:2

我有两张桌子。这些是客户和项目。每个客户都有许多项目,每个项目都与一个客户有关。我想输出视图模板中与每个客户端相关的所有项目。请帮我

Project Model

public function client()
    {
        return $this->belongsTo('App\Model\Admin\Client');
    }

Client model

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

我想在刀片模板中输出如下所示:

id -| Client_name |- client_company |- contact_number-|- project_list
----|-------------|-----------------|-----------------|-----------------
  1 |  x          |  [email protected]         |xxxxxxxxxxxxxxx  |  first project
    |             |                 |                 |  second project
    |             |                 |                 |  Third project
  ----------------|-----------------|-----------------|--------------------  
  2 |  y          |  [email protected]         |xxxxxxxxxxxxxxx  |  first project
                                    |                 |  second project
                                                      |  Third project 
php mysql laravel laravel-5 laravel-5.6
2个回答
3
投票

首先,您需要获得所有客户端的热切加载项目,如下例所示:

$ clients = Clients :: with('projects') - > get();

现在在视图模板中,您需要使用以下代码:

<?php

foreach($clients as $client) {
       // Here you can get client details in $client object
       //$client->name give you client name

   foreach($client->projects as $project){
          // Here you can get projects details in $project object
         // $project->name give you project name
   }
}

2
投票

你可以通过这种方式做到这一点

return $this->belongsTo('App\User', 'foreign_key', 'other_key');

更多Eloquent Relationships

希望这可以帮助 :)

© www.soinside.com 2019 - 2024. All rights reserved.