Laravel 5.1试图得到无对象雄辩关系的性质,处理错误


Laravel 5.1 trying to get property of non object eloquent relationship, handle error

OrganizationsController.php

public function user_index()
{   
    if(!is_null(Organization::find(Auth::user()->player->organization))) 
    $organization = Organization::find(Auth::user()->player->organization->id);
    else $organization=null;
    return view('organizations.user_index', [ 'organization' => $organization ]);
}

当"玩家"没有"组织"时,为了避免"试图获取非对象的属性",我使用了这段代码。但是它看起来不太好。有更好的方法来获得这个吗?也许我错了,但这种方法有一个无用的查询,我是对的吗?

桌面播放器:id,名称

表组织:id,name,player_id

假设user有一个playerplayer有一个organization,并且这些关系设置正确,则根本不需要Organization::find()organization属性将成为已加载的Organization对象,因此无需重新查找。

public function user_index() {
    // default to null
    $organization = null;
    // make sure there is an authenticated user and it has a player
    if (Auth::user() && Auth::user()->player) {
        // if the player has an organization, this will be the Organzation object
        // if the player does not have an organization, this will be null
        $organization = Auth::user()->player->organization;
    }
    return view('organizations.user_index', [ 'organization' => $organization ]);
}

是的,对于此检查,您可能会执行一个不必要的SQL查询。如果你这样做,你可以摆脱它:

if(Organization::find(Auth::user()->player->organization_id) 

而不是

if(!is_null(Organization::find(Auth::user()->player->organization))) 

这样,在尝试从数据库中获取组织之前,您可以检查播放器中存储的organization_id