简体   繁体   中英

Join 2 table in Eloquent ORM

I have 2 tables in my database which is :-

pams_project table has table structure project_name , dev_id (FK)
pams_developer table has table structure developer_name , id (PK)

Now, I create 2 model and make relationship between this 2 tables:-

Project.php model

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 model

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


    }
}

Now, I face a problem, I want to retrieve the developer_name and project_name from this 2 model like as the SQL below :-

 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

But I have no idea how to write in this 2 model to retrieve the data from my controllers.
Any suggestion or solution is appreaciated.

You should check laravel documentation on how to use eloquent relationships (and eager loading relationship):

https://laravel.com/docs/5.6/eloquent-relationships

For your (a bit unclear) example would be:

$developers = App\Developer::with('projects')->get();

foreach($developers as $developer) {
    echo $developer->developer_name;

    foreach($developer->projects as $project) {
        echo $project->project_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