I have the following Models
ReleasePackages
JavaScript
x
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class ReleasePackages extends Model
{
public $timestamps = false;
/**
*/
public function artifacts()
{
return $this->belongsToMany(
'AppModelsArtifacts',
'release_packages_artifacts',
'release_package_id',
'artifact_id'
);
}
public function created_by()
{
return $this->hasOne('AppModelsUsers', 'id');
}
public function approved_by()
{
return $this->hasOne('AppModelsUsers', 'id');
}
}
and Users
JavaScript
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class Users extends Model
{
public function release_packages()
{
return $this->hasOne('AppModelsReleasePackages', '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 :
JavaScript
#relations: array:3 [▼
"artifacts" => Collection {#265 ▶}
"created_by" => null
"approved_by" => null
]
how can I change the code to make the relationships works correctly ?
Advertisement
Answer
Your relationship wrong for created_by()
and approved_by()
it should be belongsTo
JavaScript
public function created_by()
{
return $this->belongsTo('AppModelsUsers', 'created_by','id');
}
public function approved_by()
{
return $this->belongsTo('AppModelsUsers', 'approved_by','id');
}