【问题标题】:How to fetch certain columns in Laravel using eloquent on "User::with" query?如何在“User::with”查询中使用 eloquent 获取 Laravel 中的某些列?
【发布时间】:2018-10-23 03:13:21
【问题描述】:

所以我在 Laravel 中用这个语句进行了雄辩的查询。它的关系都设置正确,我的问题是将它获取的数据限制在“with”数据的某些列中。

如您所见,“userIsFollowingAuthor”关系表是我作为关系包含的 3 个表之一。

但是,如何从这些单独的关系中只选择特定的列?例如我只需要上面提到的这个关系中的“first_name”和“avatar_id”,而不是完整的数据集。

$user_dashboard_data = User::with('profile', 'favorites', 'userIsFollowingAuthor')->find($user->id);

【问题讨论】:

    标签: mysql laravel eloquent


    【解决方案1】:

    您可以通过在 with 数组输入中将闭包作为值和关系作为键来限制急切加载查询:

    User::with(['userIsFollowingAuthor' => function($q) {
        $q->select(['column1', 'column2']);
    });
    

    但是,您使用的是 find(检索一个模型),因此急切加载确实没有任何好处。

    您可以使用关系方法查询任何关系:

    $user->userIsFollowingAuthor()->select(['column1', 'column2'])->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-21
      • 1970-01-01
      • 2013-11-20
      • 2019-08-01
      • 2013-04-24
      相关资源
      最近更新 更多