最好的方式来做这个列出laravel与关系

时间:2016-08-30 02:18:45

标签: laravel eloquent relationship

这个列表的最佳方式是什么?

我不想那样做"丑陋"。

/**
 * Get user indicateds
 * @return array|null
 */
static public function indicateds()
{
    $users = ModelUser::all();
    foreach( $users as $user ) {
        if( $user->financial->status_payment ) {
            $newArray[] = $user;
        }
    }
    return (isset($newArray) ? $newArray : null);
}

由于

2 个答案:

答案 0 :(得分:1)

您可以使用该集合filter method

return ModelUser::with('financial')
    ->get()
    ->filter(function($user) {
        return $user->financial->status_payment;
    });

我认为你已经定义了财务关系,你应该像我一样急于加载它以提高性能。

答案 1 :(得分:-1)

关系的一个好处是,您也可以使用它们来修改您的查询。因此,您可以使用该关系修改查询,而不是让所有用户都进入Collection,然后过滤Collection,这样您才能首先获得所需的记录。这将减少从数据库返回的记录数,以及创建的模型实例数。这将节省您的时间和记忆。

$users = ModelUser::with('financial')
    ->whereHas('financial', function($q) {
        // $q is the query for the financial relationship;
        return $q->where('status_payment', true);
    }
    ->get();

with()不是必需的,但如果您要在返回的用户上访问financial关系,最好急切加载它。

whereHas()是神奇发生的地方。它修改了查询,以便它只返回具有相关financial记录的用户,该记录与第二个参数中使用的闭包添加的条件相匹配。

您可以在documentation here中了解更多相关信息。

相关问题