Property does not exist on this Collection instance

Asked

Viewed 1,197 times

0

From what I’ve researched, it could be something related to the fact that you’re in a relationship 1:N, hasMany > belongsTo, but I don’t know what I have to do.

I’m developing a API in Laravel 5.5 and I have tables that relate when the relationship is 1:1, results normally, however, when I have tables that the relationship is 1:N, gives the message: Property does not exist on this collection instance.

Information:

The table of users [login_users] relates to the behavior table [behaviors], 1:N and in the [behaviors] only has the id.

And the behavior chart [behaviors] relates to the behavior key word table [lkp_key_behaviors], 1:1 and in the [lkp_key_behaviors], has the words of behavior as: Leadership, Organization, etc

When I change my relationship to 1:1, hasOne > belongsTo das Models LoginUser and Behavior, brings the results, but naturally does not bring all 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]);                           
}
  • One question, is this bank legacy (that is, it already existed) or is it a new bank? If you are new you have fled too much of the pattern and do not need to do as much as you are doing, these relationships can be improved.

  • It is new bank, I can modify if necessary. Any suggestions?

  • Follow the rules that are described on the site itself, an example when creating relationships is always the table name with _id example cliente_id and not that big non-standard name. https://laravel.com/docs/5.7/eloquent-relationships

  • So, what big name without default? Because table names are getting the _id at the end. The tables are receiving the name in the plural, as default and staying in this format -> Table name: login_users, primary key: login_user_id. Table name: Behaviors, primary key: behavior_id. Table name: lkp_key_behaviors, primary key: lkp_key_behavior_id. In my view this is a standard, and is in accordance with the Standard documentation. It was your suggestion?!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.