Happy Coder
Happy Coder

Reputation: 4682

How to correctly specify the relationships between Eloquent Models

I have the following Models

ReleasePackages

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ReleasePackages extends Model
{
    public $timestamps = false;

    /**
    */
    public function artifacts()
    {
        return $this->belongsToMany(
            'App\Models\Artifacts',
            'release_packages_artifacts',
            'release_package_id',
            'artifact_id'
        );
    }

    public function created_by()
    {
        return $this->hasOne('App\Models\Users', 'id');
    }

    public function approved_by()
    {
        return $this->hasOne('App\Models\Users', 'id');
    }
}

and Users

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Users extends Model
{
    public function release_packages()
    {
        return $this->hasOne('App\Models\ReleasePackages', 'created_by');
    }
}

Now for each release package, there are two columns which is related with Users. One is created_by and the other is approved_by. I am trying to set this relation by the the above code, but when I call

$packages = ReleasePackages::with(['artifacts','created_by','approved_by'])->get();

I am not getting the relations with Users. I have the corresponding user id in users table and the column name is id. I am getting the following response from the above controller code :

 #relations: array:3 [▼
        "artifacts" => Collection {#265 ▶}
        "created_by" => null
        "approved_by" => null
      ]

how can I change the code to make the relationships works correctly ?

Upvotes: 1

Views: 37

Answers (1)

Dilip Hirapara
Dilip Hirapara

Reputation: 15296

Your relationship wrong for created_by() and approved_by() it should be belongsTo

public function created_by()
{
    return $this->belongsTo('App\Models\Users', 'created_by','id');
}

public function approved_by()
{
    return $this->belongsTo('App\Models\Users', 'approved_by','id');
}

Upvotes: 2

Related Questions