我想为这个模型创建一个WithCount子查询。
多亏了
Iqbal Butt
我有这段话要数。
$count = Action::select('article_id as assigned');
if (!empty($action_type_id))
{
$count = $count->where('action_type_id', $action_type_id);
}
if (!empty($set_id))
{
$count = $count->where('set_id', $set_id);
}
$count = $count->distinct('article_id')->count('article_id');
我想这样做,但我觉得这是痛苦的缺陷。
澄清编辑
我有一个集到文章的多对多关系。
每一篇文章都有许多动作。
动作可以有多种动作类型。
我需要计算给定集合中每个项目的操作类型。
$sets = Set::withCount(['actions' => function ($q) use ($action_type_id, $set_id) {
$q->select('article_id as assigned');
if (!empty($action_type_id))
{
$q->where('action_type_id', $action_type_id);
}
if (!empty($set_id))
{
$q->where('set_id', $set_id);
}
$q->distinct('article_id')
->count('article_id');
// I believe this is executing inner query
}])
->get();
return $sets;
这给了我一个错误,更可能是因为内部查询正在执行,而没有外部查询。
sqlstate[42s22]:未找到列:1054中的未知列“sets.id”
“where子句”(sql:select count(distinct
article_id
)作为骨料
从
actions
哪里
sets
.
id
=
行动
.
set_id
和
action_type_id
=1和
塞特伊德
= 1)
按评论编辑
物品模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
/**
* Get the sets for the article.
*/
public function sets()
{
return $this->belongsToMany(Set::class);
}
public function actions()
{
return $this->hasMany(Action::class);
}
}
集合模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Set extends Model
{
/**
* Get the articles for the set.
*/
public function articles()
{
return $this->belongsToMany(Article::class);
}
public function actions()
{
return $this->hasMany(Action::class);
}
}
行动模式
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Action extends Model
{
/**
* Get the set that owns the action.
*/
public function set()
{
return $this->belongsTo(Set::class);
}
/**
* Get the article that owns the action.
*/
public function article()
{
return $this->belongsTo(Article::class);
}
}
数据库
行动
id
set_id
article_id
action_type_id
集合
id
name
物品
身份证件
名称
文章集
id
set_id
article_id