我的数据库中有2个表: -
pams_project
表格包含表格project_name
,dev_id
(FK)
pams_developer
表格具有表格结构developer_name
,id
(PK)
现在,我创建2个模型并在这两个表之间建立关系: -
Project.php
模型
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Developer;
class Project extends Model
{
protected $table = 'pams_project';
protected $primaryKey = 'project_id';
public function developer()
{
return $this->belongsTo(Developer::class,'dev_id','id');
}
}
Developer.php
型号
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Project;
class Developer extends Model
{
//
protected $table = 'pams_developer';
protected $primaryKey = 'id';
public function projects()
{
return $this->hasMany(Project::class,'dev_id','id');
}
}
现在,我遇到了一个问题,我想从这个2模型中检索developer_name和project_name,如下面的SQL: -
SELECT D.developer_name , P.project_name
FROM pams_developer AS D
JOIN pams_project AS P
ON P.dev_id = D.id
GROUP BY D.developer_name
但是我不知道怎么写这个2模型来从我的控制器中检索数据 任何建议或解决方案都是适用的。
答案 0 :(得分:0)
您应该检查laravel文档,了解如何使用雄辩的关系(以及热切的加载关系):
https://laravel.com/docs/5.6/eloquent-relationships
对于你的(有点不清楚)的例子是:
$developers = App\Developer::with('projects')->get();
foreach($developers as $developer) {
echo $developer->developer_name;
foreach($developer->projects as $project) {
echo $project->project_name;
}