Laravel belongs to throwing undefined error

别来无恙 提交于 2020-01-16 03:24:12

问题


I have 2 models.

User:

class User extends Eloquent implements UserInterface, RemindableInterface {

    protected $table = 'users';

    public function group () 
    {
        return $this->belongsTo('Group');
    }
}

And Group:

class Group extends Eloquent {
    protected $table = 'groups';
}

The user table has a foreign key on the group column which references the id on the group table.

Schema may help

Schema::table('users', function ($table) {

    $table->foreign('group')
        ->references('id')
        ->on('groups')
        ->onDelete('cascade');

});

When I try to get the group of a user using:

User::find(1)->group()->name

I get the error

Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name

Group Schema as requested:

Schema::create('groups', function ($table) {

    $table->increments('id');
    $table->string('name');
    $table->integer('permission');

});

Here are some screens:

users table

groups table:

And the users table FK

EDIT

@Cryode solved it for me in a chat session. The problem was that I had conflicting names. The model method used the same name as the column name (group). Simply changing the column name in the database solved the issue.


回答1:


After helping through chat, the problem was that there was an existing column called group, and the relationship method was also called group, so the table column value was taking precedence over the relationship method.

Renaming the relationship method, or the group column to something like group_id are both suitable solutions (I'd suggest the group_id route).


Original answer:

You retrieve the group through a magic property, not directly from the method.

echo User::find(1)->group->name;

If you retrieve the group() method, it will return the relationship object, not perform any queries and fetch the relating object.

Also, Eloquent will make assumptions as to what your foreign key column names are. Group would automatically translate to a group_id column. If you have an existing column called group, then you should specify that explicitly in your relationship:

public function group () 
{
    return $this->belongsTo('Group', 'group');
}

If you receive a "Trying to get property of non-object" error for the property group, then your relationship is not returning any results ($user->group will be NULL). At that point, you should make sure your relationship is set up properly (e.g. using the correct belongsTo, hasOne, hasMany, etc.), and ensure that you actually have a related entry in your database.



来源:https://stackoverflow.com/questions/25026123/laravel-belongs-to-throwing-undefined-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!