Sead Lab
Sead Lab

Reputation: 211

Can't Retrieve One to Many Relationship Data In Laravel

I have a bit strange of problem about retrieving one to many relationship data in Laravel.

Model

// JobTypes model
public function jobs()
{
    // one type of job has many jobs
    return $this->hasMany('App\Jobs', 'id'); // id refer to jobs.id
}

// Jobs model
public function job_types()
{
    // one job only belongs to one type of job
    return $this->belongsTo('App\jobTypes');
}

Pivot table

 Schema::create('jobs_job_types', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('jobs_id')->unsigned()->nullable();
        $table->integer('job_types_id')->unsigned()->nullable();
        $table->timestamps();

        $table->foreign('jobs_id')->references('id')->on('jobs');
        $table->foreign('job_types_id')->references('id')->on('job_types');
    });

Controller

$data = \App\JobTypes::paginate($items);

    return view('jobs.index', compact('data'))->with(array('showData' => $showData, 'count' => $count))->withItems($items);

View

@foreach($data as $jobType)
        <td>
          @foreach($jobType->jobs as $category)
            {{ $category->name }}
          @endforeach
        </td>
    @endforeach 

Am I missing something?

Upvotes: 0

Views: 69

Answers (2)

Erich
Erich

Reputation: 2626

You don't need a pivot table for a one-to-many relationship in Laravel. The child relationship (the "many" side) can simply store the id of the parent model it belongs to.

(See also my comment above about following general Laravel naming conventions.)

Models:

// JobType.php
class JobType extends Model
{
    public function jobs()
    {
        return $this->hasMany('App\Job');
    }
}

// Job.php
class Job extends Model
{
    public function job_type()
    {
        return $this->belongsTo('App\JobType');
    }
}

Migrations:

// create_job_types_table.php
    Schema::create('job_types', function (Blueprint $table) {
        $table->increments('id');
        ...
    });

// create_jobs_table.php
    Schema::create('jobs', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('job_type_id')->unsigned()->index();
        ...

        $table->foreign('job_type_id')->references('id')->on('job_types');
    });

Upvotes: 2

Daniyal Ishaq
Daniyal Ishaq

Reputation: 174

try like this:

// JobTypes model
public function jobs()
{
    // one type of job has many jobs
    return $this->hasMany(\App\Job_Type::class, 'job_id');
}

// Jobs model
public function job_types()
{
    // one job only belongs to one type of job
    return $this->belongsTo('App\jobTypes','job_type_id','id');
}

Upvotes: 1

Related Questions