【问题标题】:Laravel 5.1 trying to get property of non object eloquent relationship, handle errorLaravel 5.1试图获取非对象雄辩关系的属性,处理错误
【发布时间】:2015-08-14 13:02:02
【问题描述】:

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

【问题讨论】:

  • 你能给我你数据库的列吗?
  • 是的,谢谢。但我认为它们没用。

标签: php laravel laravel-5 eloquent laravel-5.1


【解决方案1】:

假设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 ]);
}

【讨论】:

    【解决方案2】:

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

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

    而不是

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

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

    【讨论】:

    • 实际上我没有“organization_id”...外键在组织上
    • 您能粘贴您的关系定义吗?如果玩家只能拥有一个组织,那么我希望将外键存储在玩家中
    • 好吧,玩家只能有一个组织,一个组织只能有一个玩家。我把外键放在组织上:)
    • 在这种情况下,如果不对组织表执行查询,就无法检查具有给定 player_id 的组织是否存在于数据库中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多