执行此列表 laravel 与关系的最佳方式

Best way to do this listing laravel with relationship

发布此列表的最佳方式是什么?

我不想那样做 "ugly"。

/**
 * 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);
}

谢谢

您可以使用 collection 的 filter method:

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

我假设你已经定义了 financial 关系,你应该像我一样急于加载它以提高性能。

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

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

with() 不是必需的,但如果您要访问 returned 用户的 financial 关系,则最好预先加载它。

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

您可以在 documentation here 中阅读更多相关信息。