What I researched might be something related to having 1:N
, hasMany
> belongsTo
relationship, but I do not know what I have to do.
I'm developing a API
in Laravel 5.5 and I have some tables that relate when the relationship is 1:1
, it brings the results normally, however, when I have tables the relationship is 1:N
, it gives the message: Property does not exist on this collection instance
.
Information:
The user table [login_users]
is related to the behavior table [behaviors]
, 1:N
and in [behaviors]
only has id
.
And the [behaviors]
behavior table is related to the behavior code table [lkp_key_behaviors]
, 1:1
and [lkp_key_behaviors]
, has behavior words such as: Leadership, Organization, etc.
When I change the relationship to 1:1
, hasOne
> belongsTo
of Models LoginUser
and Behavior
, brings the results, however of course does not bring all the behaviors, brings only the first.
Model: LoginUser
public function behaviors()
{
return $this->hasMany('App\Models\Behavior','login_user_id');
}
Model: Behavior
public function loginuser()
{
return $this->belongsTo('App\Models\LoginUser','login_user_id');
}
public function lkpkeybehavior()
{
return $this->hasOne('App\Models\LkpKeyBehavior','key_behavior_id');
}
Model: LkpKeyBehavior
public function behaviors()
{
return $this->belongsTo('App\Models\Behavior','key_behavior_id');
}
Controller: LoginUserController
public function show($id)
{
$loginuser = $this->loginuser->find($id);
$behavior = $loginuser->behaviors->lkpkeybehavior;
$lkpkeybehavior = $behavior->lkpkeybehavior;
return response()->json(['User Profile' => $loginuser]);
}