Laravel with method需要花费大量时间来建立M:N关系

时间:2017-10-18 12:36:20

标签: php mysql laravel laravel-5 laravel-5.4

我有三张桌子:与会者,与会者标签和代码,与会者之间的M:N关系 - 标签。表attendee_tag包含名为value的其他列。现在考虑在attendee_tag表中的800个与会者,140个标签和36,000个条目(一个与会者通常与所有标签没有关系)。

我想得到fe。 500名与会者的标签和价值观。所以我写了这个Laravel方法:

$attendees = Attendee::where('event_id', '=', $event_id)
    ->with(['tags' => function($q) {
        $q->select('tags.id', 'value_type');
    }])
    ->paginate($pagination);

这会生成以下sql查询

"log": [
    {
      "query": "select count(*) as aggregate from `attendees` where `event_id` = ?",
      "bindings": [
        "2"
      ],
      "time": 1.31
    },
    {
      "query": "select * from `attendees` where `event_id` = ? limit 500 offset 0",
      "bindings": [
        "2"
      ],
      "time": 40.99
    },
    {
      "query": "select `tags`.`id`, `value_type`, `attendee_tag`.`attendee_id` as `pivot_attendee_id`, `attendee_tag`.`tag_id` as `pivot_tag_id`, `attendee_tag`.`value_string` as `pivot_value_string`, `attendee_tag`.`value_int` as `pivot_value_int` from `tags` inner join `attendee_tag` on `tags`.`id` = `attendee_tag`.`tag_id` where `attendee_tag`.`attendee_id` in (...)",
      "bindings": [
        ...
      ],
      "time": 721.62
    }
  ]

如果我直接在数据库中运行这些查询,它们就足够快了,但是当我拨打api电话时,我等待结果28秒......为什么会如此?慢?我可以以某种方式改善它吗?

0 个答案:

没有答案