在嵌套关系上添加列
add column on a nested relationship
是否可以在嵌套关系上添加列?
例如,我有以下表格
groups
- id
- title
categories
- id
- title
- parent_id
- group_id
threads
- id
- title
- replies_count
- category_id
我想做以下事情
class GroupController extends Controller {
public function index(){
return Groups::with(['categories'])->get()
}
class Category extends Model{
protected $withCount = ['threads'];
}
因此,当我预先加载 'categories' 时,我也会预先加载与每个类别关联的每个线程。但我还想在类别模型上添加一个新列,其中一些 replies_count,与 withCount.
相同
例如
groups => [
"id" => 1,
"title" => "some-title"
"categories" => [
"id" => 1,
"title" => "category-title",
"threads_count" => 2,
"replies_count_sum" => 5
]
]
在上面的示例中,具有 id=1 的 group 具有关联的 category与之相关,并且该类别有 2 个线程 与之相关联,并且这两个线程上的 回复 总数为 5
你应该可以使用 withCount and sub Query Join
$values=Group::with(['categories'=>function($query)use(
{
$repliesSumCountForCategory=Threads::selectRaw('category_id,sum(replies_count) as replies_count_sum')->groupBy('category_id');
$query->withCount('threads');
$query->join($repliesSumCountForCategory,'replies_sum_count_for_category',
function($join)
{
$join->on('categories.id','=','replies_sum_count_for_category.category_id')
}
$query->addSelect('replies_sum_count_for_category.replies_count_sum');
}
])->get();
我没有机会测试它,如果有帮助请告诉我...
是否可以在嵌套关系上添加列?
例如,我有以下表格
groups
- id
- title
categories
- id
- title
- parent_id
- group_id
threads
- id
- title
- replies_count
- category_id
我想做以下事情
class GroupController extends Controller {
public function index(){
return Groups::with(['categories'])->get()
}
class Category extends Model{
protected $withCount = ['threads'];
}
因此,当我预先加载 'categories' 时,我也会预先加载与每个类别关联的每个线程。但我还想在类别模型上添加一个新列,其中一些 replies_count,与 withCount.
相同例如
groups => [
"id" => 1,
"title" => "some-title"
"categories" => [
"id" => 1,
"title" => "category-title",
"threads_count" => 2,
"replies_count_sum" => 5
]
]
在上面的示例中,具有 id=1 的 group 具有关联的 category与之相关,并且该类别有 2 个线程 与之相关联,并且这两个线程上的 回复 总数为 5
你应该可以使用 withCount and sub Query Join
$values=Group::with(['categories'=>function($query)use(
{
$repliesSumCountForCategory=Threads::selectRaw('category_id,sum(replies_count) as replies_count_sum')->groupBy('category_id');
$query->withCount('threads');
$query->join($repliesSumCountForCategory,'replies_sum_count_for_category',
function($join)
{
$join->on('categories.id','=','replies_sum_count_for_category.category_id')
}
$query->addSelect('replies_sum_count_for_category.replies_count_sum');
}
])->get();
我没有机会测试它,如果有帮助请告诉我...