【问题标题】:Laravel 5.8 pluck a relationship and use a local scope for that relationshipLaravel 5.8 提取关系并为该关系使用本地范围
【发布时间】:2019-10-20 08:57:05
【问题描述】:

这看起来很简单,但没有任何运气。我有一对多 TaskBlock 的关系。关系: Task->blocks:

public function blocks()
{
    return $this->hasMany(Block::class, 'task_uuid', 'task_uuid');
}

Blocks->task:

public function task()
{
    return $this->belongsTo(Task::class, 'task_uuid', 'task_uuid');
}

有了它,我可以像这样获得任务的所有块:$task->blocks;。我正在尝试从一组任务中提取所有内容:$tasks->pluck('blocks') 并使用Block 模型上的本地范围:

public function scopeUnresolved($query)
{
    return $query->where('resolved_at', null);
}

我的一些尝试(甚至是超级愚蠢的尝试): $tasks->pluck('blocks')->unresolved()->get(); $tasks->pluck('blocks')->flatten()->unresolved()->get(); $tasks->pluck('blocks')->filter()->get()->unresolved()->get(); 以及其他一些人。我已经让这个工作了:

$tasks->pluck('blocks')->flatten()->filter(function ($block) {
    return $block->unresolved()->get();
});

似乎有一种更简洁的方式来解决它,但也许不是?对此有何见解?谢谢!

【问题讨论】:

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


    【解决方案1】:

    这可以在查询您的$tasks 时完成;如果您等到已经拉出Task 模型之后,您可能不得不循环执行,这是一个 n+1 问题。尝试使用“急切加载”:

    $tasks = Task::with(["blocks" => function($subQuery){
      $subQuery->whereNull("resolved_at");
      // or, if you want to use your `scopeUnresolved()`
      $subQuery->unresolved();
    }])->get();
    

    注意:where("unresolved_at", null) 可能有效也可能无效,但有一个 whereNull() 方法

    现在,当您尝试访问任务的块时,它只会包含未解决的块:

    foreach($tasks AS $task){
      dd($task->blocks);
      // etc.
    }
    

    【讨论】:

      猜你喜欢
      • 2019-09-18
      • 1970-01-01
      • 2020-04-17
      • 2015-12-02
      • 1970-01-01
      • 1970-01-01
      • 2020-01-07
      • 2020-05-13
      • 2019-11-17
      相关资源
      最近更新 更多