Laravel 5.1 试图获取 属性 的非对象 eloquent 关系,处理错误
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 ]);
}
为了在 "player" 没有 "organization" 时避免 "Trying to get property of non-object",我使用了这段代码。但它似乎不太好。有没有更好的方法来获得这个?也许我错了,但是使用这种方法有一个无用的查询,对吗?
Table 玩家: id, name
Table 组织:id,名称,player_id
是的,对于此检查,您可能会执行一个不必要的 SQL 查询。如果你这样做,你可以摆脱这个:
if(Organization::find(Auth::user()->player->organization_id)
而不是
if(!is_null(Organization::find(Auth::user()->player->organization)))
通过这种方式,您可以在尝试获取 organization[之前检查存储在 player 中的 organization_id =21=] 来自数据库。
假设 user
有一个 player
,并且 player
有一个 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 ]);
}
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 ]);
}
为了在 "player" 没有 "organization" 时避免 "Trying to get property of non-object",我使用了这段代码。但它似乎不太好。有没有更好的方法来获得这个?也许我错了,但是使用这种方法有一个无用的查询,对吗?
Table 玩家: id, name
Table 组织:id,名称,player_id
是的,对于此检查,您可能会执行一个不必要的 SQL 查询。如果你这样做,你可以摆脱这个:
if(Organization::find(Auth::user()->player->organization_id)
而不是
if(!is_null(Organization::find(Auth::user()->player->organization)))
通过这种方式,您可以在尝试获取 organization[之前检查存储在 player 中的 organization_id =21=] 来自数据库。
假设 user
有一个 player
,并且 player
有一个 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 ]);
}